Description
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.
Solution 1(C++)
class Solution {
private:
vector<vector<int>> dire={{-1,0}, {0,-1}, {1,0}, {0,1}};
bool dfs(vector<vector<char>>& board, int x, int y, string word, int index){
if(index==word.size()-1 && board[x][y]==word[index]) return true;
if(board[x][y]=='*' || board[x][y]!=word[index]) return false;
else{
char temp=board[x][y];
board[x][y]='*';
for(int i=0; i<4; i++){
if(x+dire[i][0]<0 || x+dire[i][0]>=board.size()) continue;
if(y+dire[i][1]<0 || y+dire[i][1]>=board[0].size()) continue;
if(dfs(board, x+dire[i][0], y+dire[i][1], word, index+1)) return true;
}
board[x][y]=temp;
return false;
}
}
public:
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++){
int index=0;
if(dfs(board, i, j, word, index)) return true;
}
}
return false;
}
};
Solution 2(C++)
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if(board.size() < 1 || board[0].size() < 1 || word.size() < 1)
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] && helper(board, word, 1, i, j))
return true;
}
}
return false;
}
bool helper(vector<vector<char>> &board, string &word, int len, int row, int column)
{
if(len == word.size())
return true;
char tmp = board[row][column];
board[row][column] = '@';
if(row > 0 && board[row-1][column] == word[len] && helper(board, word, len+1, row-1, column))
return true;
if(column > 0 && board[row][column-1] == word[len] && helper(board, word, len+1, row, column-1))
return true;
if(row < board.size()-1 && board[row+1][column] == word[len] && helper(board, word, len+1, row+1, column))
return true;
if(column < board[0].size()-1 && board[row][column+1] == word[len] && helper(board, word, len+1, row, column+1))
return true;
board[row][column] = tmp;
return false;
}
};
算法分析
比较经典的深度优先搜索了,注意代码编写即可。适合多多练习。
程序分析
略。