LeetCode79.单词搜索(经典DFS)

在这里插入图片描述
dfs出口说明:搜索中dfs参数 u = 1 u=1 时已经搜到了2个数,所以你要搜n个数,那设置出口 u = n 1 u=n−1 即可

C++代码

class Solution {
public:
    static const int N = 1000;
    int n, m;
    int dx[4] = {0, 0, 1, -1}, dy[4] = {1, -1, 0, 0};
    bool st[N][N];

    bool exist(vector<vector<char>>& board, string word) {
        if(board.empty() || board[0].empty()) return false;

        n = board.size(), m = board[0].size();
        for (int i = 0; i < n; i ++) {
            for (int j = 0; j < m; j ++) {
                st[i][j] = true; // 把起点设为访问过的点
                if(board[i][j] == word[0] && dfs(board, i, j, word, 0)) return true;
                st[i][j] = false;
            }
        }
        return false;
    }

    bool dfs(vector<vector<char>> & board, int sx, int sy, string & word, int u) {
        if (u == word.size() - 1) return true;
    
        for (int i = 0; i < 4; i ++) {
            int a = sx + dx[i], b = sy + dy[i];
            // 3个if用来剪枝,类似n皇后的if条件
            if (a < 0 || a >= n || b < 0 || b >= m) continue;
            if (st[a][b] == true) continue;
            if (board[a][b] != word[u + 1]) continue;

            st[a][b] = true;
            if (dfs(board, a, b, word, u + 1)) return true; // 只要有一个是true就会一直返回true
            st[a][b] = false;  // 恢复现场,不影响其他分支
        }
       
        return false;
    }

};
发布了182 篇原创文章 · 获赞 71 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_43827595/article/details/103967940