题目:给一个字符矩阵,在里面找单词。相邻字母必须要4邻域内。
分析:典型的4邻域深度优先搜索,
答案:
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
M = board.size();
N = board[0].size();
for (int i = 0; i < M; i ++)
for (int j = 0; j < N; j++){
if (dfs(board, word.c_str(), i, j)){
return true;
}// start dfs from 0,0
}
return false;
}
private:
int M,N;
bool dfs(vector<vector<char>>& board,const char * word, int x, int y){
if (x<0 || y<0 || x >= M || y >=N || board[x][y] != *word )
return false;
if (*(word +1)=='\0')
return true;
// back tracking
char temp = board[x][y];
board[x][y] = '\0';
if(dfs(board, word+1, x+1,y) || dfs(board, word+1, x-1,y) ||dfs(board, word+1, x,y+1) ||dfs(board, word+1, x,y-1))
return true;
board[x][y] = temp;
return false;
}
};