题解 | #矩阵中的路径#

矩阵中的路径

https://www.nowcoder.com/practice/2a49359695a544b8939c77358d29b7e6

#include <vector>
class Solution {
public:
    bool hasPath(vector<vector<char> >& matrix, string word) {
        if (matrix.empty()) return false;
        int rows = matrix.size();
        int cols = matrix[0].size();
        vector<vector<bool> > state(rows, vector<bool>(cols, false));
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                if (dfs(matrix, rows, cols, i, j, state, word, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    bool dfs(vector<vector<char> >& matrix, int rows, int cols, int i, int j,
        vector<vector<bool> >& state, const string& word, int word_idx) 
    {
        if (i < 0 || i >= rows) return false;
        if (j < 0 || j >= cols) return false;
        if (matrix[i][j] != word[word_idx]) return false;
        if (state[i][j]) return false;
        
        if (word_idx == word.length() - 1) return true;
        state[i][j] = true;
        if (
            dfs(matrix, rows, cols, i-1, j, state, word, word_idx + 1) ||
            dfs(matrix, rows, cols, i+1, j, state, word, word_idx + 1) ||
            dfs(matrix, rows, cols, i, j+1, state, word, word_idx + 1) ||
            dfs(matrix, rows, cols, i, j-1, state, word, word_idx + 1)
        ) {
            return true;
        }
        state[i][j] = false;
        return false;
    }
};

2023-剑指-回溯 文章被收录于专栏

2023-剑指-回溯

全部评论

相关推荐

点赞 评论 收藏
分享
不要停下啊:大二打开牛客,你有机会开卷了,卷起来,去找课程学习,在牛客上看看大家面试笔试都需要会什么,岗位有什么需求就去学什么,努力的人就一定会有收获,这句话从来都经得起考验,像我现在大三了啥也不会,被迫强行考研,炼狱难度开局,啥也不会,找工作没希望了,考研有丝丝机会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务