LeetCode-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.

解题思路:深度优先搜索。注意边界条件。

    bool exist(vector<vector<char>>& board, string word) {
        for(int i =0; i < board.size(); i++){
            for(int j=0; j < board[0].size(); j++){
                if(exists(board,word, i,j, 0))
                    return true;
            }
        }
        return false;
    }
    
    bool exists(vector<vector<char>>& board, string word, int i, int j, int start){
        if(start >= word.size()) return true;
        if( i<0 || i >= board.size() || j < 0 || j >= board[0].size()) return false;
        if(board[i][j]==word[start]){
            char c = board[i][j];
            board[i][j] = '#';
            bool res = exists(board, word, i+1, j, start+1) ||
                exists(board,word,i-1,j,start+1) ||
                exists(board,word,i,j+1,start+1) ||
                exists(board,word,i,j-1,start+1);
            board[i][j] = c;
            return res;
        }
        return false;
    }

 

posted on 2019-02-01 10:46  无名路人甲  阅读(89)  评论(0编辑  收藏  举报