Leetcode 79. 单词搜索

暴力深搜

class Solution {
public:
    vector<vector<bool>> vis;
    int n, m, dx[4] = { -1,1,0,0 }, dy[4] = { 0,0,1,-1 };
    bool _place(int i, int j) { return i >= 0 && i < n &&j >= 0 && j < m; }
    bool dfs(vector<vector<char>>& board, string &word, int index, int row, int col) {
        if (index == word.size()) return true;
        for (int k = 0; k < 4; ++k) {
            int i = row + dx[k], j = col + dy[k];
            if (_place(i, j) && !vis[i][j] && board[i][j] == word[index]) {
                vis[i][j] = 1;
                if (dfs(board, word, index + 1, i, j)) return true;
                vis[i][j] = 0;
            }
        }
        return false;
    }
    bool exist(vector<vector<char>>& board, string word) {
        n = board.size(), m = n == 0 ? 0 : board[0].size();
        vis.assign(n, vector<bool>(m, false));
        for (int i = 0; i<n; ++i)
            for (int j = 0; j<m; ++j)
                if (board[i][j] == word[0]) {
                    vis[i][j] = 1;
                    if (dfs(board, word, 1, i, j)) return true;
                    vis[i][j] = 0;
                }
        return false;
    }
};
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Bendaai/article/details/80351846
个人分类: LeetCode
上一篇Leetcode 78. 子集
下一篇Leetcode 80. 删除排序数组中的重复项 II
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭