79. Word Search

Posted duan-decode

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了79. Word Search相关的知识,希望对你有一定的参考价值。

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.
class Solution {
    public:
        //遍历回溯,采取一个特殊处理:如果匹配到相同字符,则将该字符先置为‘0‘,回溯时恢复原字符,以免重复使用
    bool exist(vector<vector<char>>& board, string word) {
        if(board.size()==0){
                return false;
        }
        for(int i=0; i<board.size(); ++i){
            for(int j=0; j<board[0].size(); ++j){
                if(dfs(board, i, j, word, 0))
                    return true;
            }
        }
        return false;
    }
    bool dfs(vector<vector<char> >& board, int i, int j, string word, int index){
        if(index>=word.size())         //搜索完成条件
            return true;
        if(i<0||i>=board.size()||j<0||j>=board[0].size())    //搜索结束(不成功)条件
            return false;
        if(board[i][j]!=word[index]){   //当前不匹配
            return false;
        }
        char temp = board[i][j];         //当前匹配,并从邻域搜索是否匹配
        board[i][j]=0;
        bool res = dfs(board, i+1, j, word, index+1)||dfs(board, i, j+1, word, index+1)||dfs(board, i-1, j, word, index+1)||dfs(board, i, j-1, word, index+1);
        board[i][j]=temp;
        return res;
    }
};

 

以上是关于79. Word Search的主要内容,如果未能解决你的问题,请参考以下文章

79. Word Search

79. Word Search

LeetCode79. Word Search

79. Word Search

79. Word Search

79. Word Search