力扣79. 单词搜索(网格DFS + 回溯)

 比较常规的多起点搜索问题

 1 class Solution {
 2 public:
 3     typedef pair<int, int> pii;
 4     int m, n;
 5     vector<pii> start;
 6     vector<vector<char>> board;
 7     vector<int> next = {1, 0, -1, 0, 0, 1, 0, -1};
 8     bool visited[10][10] = {false};
 9     bool result = false;
10     string word;
11     void dfs_back_travel(pii p, int key_index) { //(当前点位,当前需要匹配字符的下标)
12         if (key_index == word.size()) {
13             result = true;
14             return;
15         }
16         visited[p.first][p.second] = true;
17         char key = word[key_index];
18         int x = p.first, y = p.second;
19         for (int i = 0; i < 4; ++i) {
20             if (result) return;
21             int next_x = x + next[i * 2], next_y = y + next[i * 2 + 1];
22             if (next_x >= 0 && next_x < m && next_y >= 0 && next_y < n) {
23                 if (!visited[next_x][next_y] && board[next_x][next_y] == key) {
24                     dfs_back_travel(make_pair(next_x, next_y), key_index + 1);
25                     visited[next_x][next_y] = false;
26                 }
27             }
28         }
29     }
30     bool exist(vector<vector<char>>& board, string word) {
31         this -> board = board;
32         this -> word = word;
33         m = board.size();
34         n = board[0].size();
35         for (int i = 0; i < m; ++i) {
36             for (int j = 0; j < n; ++j) {
37                 if (board[i][j] == word[0] && !result) {
38                     memset(visited, false, sizeof(visited));
39                     dfs_back_travel(make_pair(i, j), 1); //下标从1开始,因为第0个字符已经匹配
40                 }
41             }
42         }
43         return result;
44     }
45 };

 

posted on 2025-02-20 17:22  Coder何  阅读(18)  评论(0)    收藏  举报