Leetcode#79 Word Search

时间:2022-11-23 18:46:27

原题地址

依次枚举起始点,DFS+回溯

代码:

 bool dfs(vector<vector<char> > &board, int r, int c, string word) {
int m = board.size();
int n = board[].size();
int dir[][] = {{-, }, {, }, {, -}, {, }}; if (word.empty())
return true; if (r >= && r < m && c >= && c < n && board[r][c] == word[]) {
for (int i = ; i < ; i++) {
char tmp = board[r][c];
board[r][c] = ;
if (dfs(board, r + dir[i][], c + dir[i][], word.substr()))
return true;
board[r][c] = tmp;
}
} return false;
} bool exist(vector<vector<char> > &board, string word) {
if (board.empty() || board[].empty()) return false; int m = board.size();
int n = board[].size(); for (int i = ; i < m; i++)
for (int j = ; j < n; j++)
if (dfs(board, i, j, word))
return true; return false;
}