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.
2 尝试解
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if(word.size() == 0) return true;
if(board.size()==0|| board[0].size()==0 ) return false;
for(int i = 0; i < board.size();i++){
for(int j = 0; j < board[0].size();j++){
if(board[i][j] == word[0]){
board[i][j] = '0';
if(find(board,word.substr(1),i,j)) return true;
board[i][j] = word[0];
}
}
}
return false;
}
bool find(vector<vector<char>>& board, string word,int row,int column){
if(word.size()==0) return true;
if(row>0 && board[row-1][column] == word[0]){
board[row-1][column] = '0';
if(find(board,word.substr(1),row-1,column)) return true;
board[row-1][column] = word[0];
}
if(column>0 && board[row][column-1] == word[0]){
board[row][column-1] = '0';
if(find(board,word.substr(1),row,column-1)) return true;
board[row][column-1] = word[0];
}
if(row < board.size()-1 && board[row+1][column] == word[0]){
board[row+1][column] = '0';
if(find(board,word.substr(1),row+1,column)) return true;
board[row+1][column] = word[0];
}
if((column < board[0].size()-1) && board[row][column+1] == word[0]){
board[row][column+1] = '0';
if(find(board,word.substr(1),row,column+1)) return true;
board[row][column+1] = word[0];
}
return false;
}
};
3 标准解
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if (word.empty()) return true;
if (board.empty() || board[0].empty()) return false;
m = board.size();
n = board[0].size();
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
// traverse the board to find the first char
if (dfsSearch(board, word, 0, i, j)) return true;
return false;
}
private:
int m;
int n;
bool dfsSearch(vector<vector<char>>& board, string& word, int k, int i, int j) {
if (i < 0 || i >= m || j < 0 || j >= n || word[k] != board[i][j]) return false;
if (k == word.length() - 1) return true; // found the last char
char cur = board[i][j];
board[i][j] = '*'; // used
bool search_next = dfsSearch(board, word, k+1, i-1 ,j)
|| dfsSearch(board, word, k+1, i+1, j)
|| dfsSearch(board, word, k+1, i, j-1)
|| dfsSearch(board, word, k+1, i, j+1);
board[i][j] = cur; // reset
return search_next;
}
};