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;
    }


};
全部评论

相关推荐

萧索X:写篮球联赛干嘛,陪老板打篮球吗。还有实习经历要写自己所在岗位具体完成什么工作,自己的任务具体完成了什么需求,给公司带来了哪些量化增长
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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