首页 > 其他 > 详细

矩阵中的路径

时间:2020-07-16 23:16:56      阅读:58      评论:0      收藏:0      [点我收藏+]

本题考察的是回溯算法,注意C++里面数组作为形参最好写成const char* matrix,而不要写成char matrix[]

C++版本

#include <iostream>
#include <vector>
using namespace std;

bool hasPathCore(char matrix[], int rows, int cols, int row, int col, char str[], int& pathLength, bool visited[]){
    // 如果找到路径
    if(str[pathLength] == ‘\0‘)
        return true;
    bool hasPath = false;
    if(row>=0 && row<rows && col >=0 && col <cols && matrix[row*cols+col] == str[pathLength] && !visited[row*cols+col]){
        pathLength++;
        visited[row*cols+col] = true;
        // 往左寻找
        bool leftPath = hasPathCore(matrix, rows, cols, row, col-1, str, pathLength, visited);
        // 往右寻找
        bool rightPath = hasPathCore(matrix, rows, cols, row, col+1, str, pathLength, visited);
        // 往上寻找
        bool upPath = hasPathCore(matrix, rows, cols, row-1, col, str, pathLength, visited);
        // 往下寻找
        bool downPath = hasPathCore(matrix, rows, cols, row+1, col, str, pathLength, visited);
        hasPath = leftPath || rightPath || upPath || downPath;
        // 如果此路不通
        if(!hasPath){
            pathLength--;
            visited[row*cols+col] = false;
        }
    }
    return hasPath;
}

bool hasPath(char matrix[], int rows, int cols, char str[]){
    if(matrix == nullptr ||rows < 1 || cols < 1 || str == nullptr)
        return false;
    bool *visited = new bool[rows*cols];
    memset(visited, false, sizeof(visited));
    int pathLength = 0;
    for(int row = 0; row < rows; row++){
        for(int col = 0; col < cols; col++)
        {
            if(hasPathCore(matrix, rows, cols, row, col, str, pathLength, visited))
                return true;
        }
    }
    delete[] visited;
    return false;
}

int main(){
    int a[5] = {1,2,3,4,5};
    cout<<&a[2]<<" "<<&a[3]<<endl;
    cout<<Fibonacci(6)<<endl;
    return 0;
}

矩阵中的路径

原文:https://www.cnblogs.com/flyingrun/p/13325450.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!