力扣 题目79- 单词搜索

题目

题解

回溯算法 找到开头然后对上下左右四个方向 回溯 已经遍历过的至* 直到长度与word一致

代码

 1 #include<iostream>
 2 #include<vector>
 3 #include<unordered_map>
 4 using namespace std;
 5 //1是上 2是下 3是左 4是右
 6 bool loop(vector<vector<char>>& board, string& word, int x, int y, int cnt) {
 7     if (y < 0 || x < 0 || x >= board.size() || y >= board[0].size() || board[x][y] != word[cnt]) {
 8         return 0;
 9     }
10     cnt += 1;
11     if (cnt == word.size()) {
12         return 1;
13     }
14     char keep = board[x][y];
15     board[x][y] = '*';
16     //
17     if (loop(board, word, x - 1, y, cnt)) {
18         return 1;
19     }
20     //
21     if (loop(board, word, x + 1, y, cnt)) {
22         return 1;
23     }
24     //
25     if (loop(board, word, x, y - 1, cnt)) {
26         return 1;
27     }
28     //
29     if (loop(board, word, x, y + 1, cnt)) {
30         return 1;
31     }
32     board[x][y] = keep;
33     return 0;
34 }
35 //只看右和下
36 class Solution {
37 public:
38     bool exist(vector<vector<char>>& board, string word) {
39         //如果word长度比board大直接返回0
40         if (board.size() * board[0].size() < word.size()) {
41             return 0;
42         }
43         //找到开头进行回溯
44         for (int i = 0; i < board.size(); i++) {
45             for (int j = 0; j < board[i].size(); j++) {
46                 if (board[i][j] == word[0]) {
47                     int x = i;
48                     int y = j;
49                     int succes = loop(board, word, x, y, 0);
50                     if (succes) {
51                         return true;
52                     }
53                 }
54             }
55         }
56         return 0;
57     }
58 };
59 int main() {
60     Solution sol;
61     vector<vector<char>> board = { {'A', 'B', 'C', 'E'},{'S', 'F', 'C', 'S' },{'A', 'D', 'E', 'E'}};
62     string word = "ABCCED";
63     bool result=sol.exist(board, word);
64     cout << result << endl;
65     }
View Code

 

posted @ 2022-07-02 15:23  无聊的阿库娅  阅读(8)  评论(0编辑  收藏  举报