C/C++面试题—矩阵中的路径【回溯法应用】

题目描述

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。
例如 a b c e s f c s a d e e 矩阵中包含一条字符串”bcced”的路径,但是矩阵中不包含”abcb”路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

解题思路

和马踏棋盘的思路一样,都是采用回溯法。如果走到某一个结点,继续从这个节点出发,如果走到头了,就回溯到该结点,从这个节点的其他结点再次尝试。

解题代码

#include <iostream>
using namespace std;
/*
题目描述:

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。
路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。
如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。
例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,
因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

*/
class SolutionHasPath {
public:
    bool hasPath(char* matrix, int rows, int cols, char* str)
    {
        if (nullptr == matrix || rows <= 0 || cols <= 0 || nullptr == str)
            return false;
        bool *visited = new bool[rows*cols]{ false };
        int pathLen = 0;
        bool result = false;
        for (int row = 0; row < rows; row++)
        {
            for (int col = 0; col < cols; col++)
            {
                result = hasPathCore(matrix, row, rows, col, cols, str, pathLen, visited);
                if (result) //找一条路
                    break;
            }
        }
        delete[] visited;
        return result;
    }
    bool hasPathCore(char* matrix, int row, int rows,int col, int cols, char* str, int &pathLen,bool *visited)
    {
        if (str[pathLen] == '\0')
            return true;
        bool isPathNode = false;
        if (row >= 0 && row < rows && col >= 0 && col < cols
            && str[pathLen] == matrix[row*cols + col] && !visited[row*cols + col])  //和当前节点匹配,继续往下走
        {
            pathLen++;
            visited[row*cols + col] = true;
            isPathNode = hasPathCore(matrix, row-1, rows, col, cols, str, pathLen, visited) 
                || hasPathCore(matrix, row+1, rows, col, cols, str, pathLen, visited)
                || hasPathCore(matrix, row, rows, col-1, cols, str, pathLen, visited)
                || hasPathCore(matrix, row, rows, col+1, cols, str, pathLen, visited);
            if (!isPathNode)    //没有一条路行的通,回溯
            {
                pathLen--;
                visited[row*cols + col] = false;
            }
        }
        return isPathNode;
    }

};

int main(int argc, char *argv[])
{
    SolutionHasPath Path;
    //"ABCESFCSADEE", 3, 4, "SEE"
    char matrix[] = {
        'A','B','C','E',
        'S','F','C','S',
        'A','D','E','E'
    };
    char *str = "SEE";
    bool result = Path.hasPath(matrix,3,4,str);
    cout << "有没有路径:" << result << endl;
    return 0;
}

运行测试

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_29542611/article/details/80451604
今日推荐