深度优先搜索,回溯法。
- 这种问题就是在函数的开头判断结束和下面的处理函数时要特别注意。
- 还有就是在需要访问过与否的信息时,需要额外的空间,传递的是引用,改为访问过之后还有改为未访问过;这里有一个小技巧可以避免空间的使用,就是存储访问过的变化,改完之后还要改回来。
C++代码:
class Solution {
public:
/**
* @param board: A list of lists of character
* @param word: A string
* @return: A boolean
*/
bool exist(vector<vector<char> > &board, string word) {
if (word.size() == 0) {
return true;
}
if (board.size()==0 || board[0].size()==0) {
return false;
}
if (board[0].size()==1&&word.size()==1){
return board[0][0]==word[0];
}
int m = board.size();
int n = board[0].size();
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
vector<vector<bool>> visited(m,vector<bool>(n,false));
if (match(board,visited,i,j,word)) {
return true;
}
}
}
return false;
}
bool match(vector<vector<char>> & board, vector<vector<bool>>& visited, int i, int j, string word) {
if (word.size()==0) {
return true;
}
if (i<0||i>=visited.size()||j<0||j>=visited[0].size()) {
return false;
}
if (board[i][j] == word[0]&& !visited[i][j]) {
visited[i][j] = true;
bool res = (match(board,visited,i-1,j,word.substr(1))||match(board,visited,i+1,j,word.substr(1))||match(board,visited,i,j-1,word.substr(1))||match(board,visited,i,j+1,word.substr(1)));
visited[i][j] = false;
return res;
}
return false;
}
};