zoukankan      html  css  js  c++  java
  • LeetCode 79. Word Search单词搜索 (C++)

    题目:

    Given a 2D board and a word, find if the word exists in the grid.

    The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

    Example:

    board =
    [
      ['A','B','C','E'],
      ['S','F','C','S'],
      ['A','D','E','E']
    ]
    
    Given word = "ABCCED", return true.
    Given word = "SEE", return true.
    Given word = "ABCB", return false.

    分析:

    给定一个二维网格和一个单词,找出该单词是否存在于网格中。

    单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

    一道搜索的题目,有点类似走迷宫,只不过按照给定单词字母顺序来寻找,遍历board中每一个元素,判断与word中的第一个字母是否相同,如果相同则在当前位置上去搜索上下左右相邻的单元格的元素是否和当前字母的下一个字母相同,不在搜索范围内或者字母不同就返回false,当搜索的字母数等于word的长度时,也就表明在board找到了这个word。注意每次判断一个字母要标记当前位置以搜索过,以防止字母重复利用。我选择直接更改board元素,以便在后续的判断中不会重复判断此位置,在搜索结束后改回来就可以了。

    程序:

    class Solution {
    public:
        bool exist(vector<vector<char>>& board, string word) {
            h = board.size();
            w = board[0].size();
            for(int i = 0; i < h; i++){
                for(int j = 0; j < w; ++j){
                    if(searchexist(board, word, 0, i, j)) return true;
                }
            }
            return false;
        }
        int searchexist(vector<vector<char>>& board, string &word, int n, int x, int y){
            if(x < 0 || x > h-1 || y < 0 || y > w-1 || word[n] != board[x][y])
                return 0;
            if(n == word.length()-1)
                return 1;
            char temp = board[x][y];
            board[x][y] = 0;
            int flag = searchexist(board, word, n+1, x+1, y)
                     ||searchexist(board, word, n+1, x-1, y)
                     ||searchexist(board, word, n+1, x, y+1)
                     ||searchexist(board, word, n+1, x, y-1);
            board[x][y] = temp;
            return flag;
        }
    private:
        int h, w;
    };
  • 相关阅读:
    状压DP
    题解:中位数
    题解:三只小猪
    二分图最大匹配
    AC自动机
    题解 P1137 【旅行计划】
    题解 P1280 【尼克的任务】
    DFT&IDFT学习笔记
    emacs配置
    莫比乌斯反演推导即μ函数的证明
  • 原文地址:https://www.cnblogs.com/silentteller/p/11128108.html
Copyright © 2011-2022 走看看