LeetCode HOT100 - 单词搜索

回溯

当前在找 word 的下标和当前的位置

如果不同直接退出

如果相同那么就从相邻的继续

已经被探索过的直接跳过

该位置相邻的都查看过后回溯状态

class Solution {
public:
    int dx[4] = {1, 0, -1, 0};
    int dy[4] = {0, 1, 0, -1};
    
    bool exist(vector<vector<char>>& a, string word) {
        int len = word.size();
        int n = a.size();
        int m = a[0].size();
        vector<vector<int>> vis(n, vector<int>(m, 0));
        
        auto dfs = [&](this auto&& self, int k, int x, int y) -> bool {
            if (a[x][y] != word[k]) {
                return false;
            }
            if (k == len - 1) {
                return true;
            }
            vis[x][y] = 1;
            for (int i = 0; i < 4; i++) {
                int xx = x + dx[i];
                int yy = y + dy[i];
                if (xx < 0 || xx >= n || yy < 0 || yy >= m) continue;
                if (vis[xx][yy]) continue;
                if (self(k + 1, xx, yy)) {
                    vis[x][y] = 0;
                    return true;
                }
            }
            vis[x][y] = 0;
            return false;
        };
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (dfs(0, i, j)) {
                    return true;
                }
            }
        }
        return false;
    }
};
posted @ 2026-04-29 01:02  rdcamelot  阅读(15)  评论(0)    收藏  举报