题解 | #矩阵中的路径#

矩阵中的路径

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-剑指-回溯

全部评论

相关推荐

昨天 22:55
已编辑
叮咚买菜
牛客吹哨人:建议细说...哨哥晚点统一更新到黑名单:不要重蹈覆辙!25届毁意向毁约裁员黑名单https://www.nowcoder.com/discuss/1317104
叮咚买菜稳定性 10人发布 投递叮咚买菜等公司10个岗位 >
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务