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;
    }
};

 

posted @ 2018-09-22 22:03  康托漫步  阅读(140)  评论(0编辑  收藏  举报