c++

矩阵中的路径

http://www.nowcoder.com/questionTerminal/c61c6999eecb4b8f88a98f66b273a3cc

class Solution {
public:

    bool dfs(char* matrix, int row, int col, int rows, int cols, char* str, int len, vector<vector<bool> >& visit) {
        if (str[len] == '\0') return true;
        if (row < 0 || row >= rows || col < 0 || col >= cols) return false;
        const int dx[4] = {-1,0,1,0};
        const int dy[4] = {0,1,0,-1};
        if (!visit[row][col] && matrix[row*cols+col] == str[len]) {
            visit[row][col] = true;
            for (int i = 0; i < 4; ++ i) {
                if (dfs(matrix, row+dx[i], col+dy[i], rows, cols, str, len+1, visit)) return true;
            }
            visit[row][col] = false;
        }
        return false;
    }

    bool hasPath(char* matrix, int rows, int cols, char* str)
    {
        if (matrix == NULL || rows == 0 || cols == 0 || str == NULL) return false;
        vector<vector<bool> > visit(rows, vector<bool>(cols, false));
        int len = 0;
        for (int i = 0; i < rows; ++ i) {
            for (int j = 0; j < cols; ++ j) {
                if (dfs(matrix, i, j, rows, cols, str, len, visit)) return true;
            }
        }
        return false;
    }


};
全部评论

相关推荐

2025-12-03 03:32
安徽大学 Java
点赞 评论 收藏
分享
2025-12-01 15:04
吉首大学 后端工程师
冲鸭2024:亚信不去也罢
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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