题解
深度优先搜索
class Solution {
public:
int n, m;
int lenw;
int visit[201][201];
int dirx[4] = {0, 1, 0, -1};
int diry[4] = {1, 0, -1, 0};
bool exist(vector<vector<char>>& board, string word) {
n = board.size();
m = board[0].size();
char ss = word[0];
lenw = word.length();
bool flag = false;
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
memset(visit, 0, sizeof(visit));
if (board[i][j] == ss) {
int k = 0;
visit[i][j] = 1;
flag = DFS(i, j, k, word, board);
if (flag) return true;
}
}
}
return false;
}
bool DFS(int x, int y, int k, string word, const vector<vector<char>>& board) {
if (k==lenw-1) {
return true;
}
for(int i=0; i<4; i++) {
int dx = x + dirx[i];
int dy = y + diry[i];
if(dx>=0 && dx<n && dy>=0 && dy<m && !visit[dx][dy]) {
int kt = k+1;
if (board[dx][dy] == word[kt]) {
visit[dx][dy] = 1;
bool flag = DFS(dx, dy, kt, word, board);
if (flag) return true;
visit[dx][dy] = 0;
}
}
}
return false;
}
};