【剑指offer】面试题12 - 矩阵中的路径

面试题12:矩阵中的路径

题目描述:

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用下划线标出)。但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。
在这里插入图片描述

链接:LeetCode 牛客网

解法一:DFS + 回溯

class Solution {
public:
    bool hasPath(string matrix, int rows, int cols, string str) {
        // write code here
        if(str.size() == 0 || rows <= 0 || cols <= 0 || matrix.size() == 0) return false;
        bool *vis = new bool[rows * cols];
        memset(vis, 0, rows * cols);
        int pathLength = 0;
        for(int i = 0; i < rows; i++)
            for(int j = 0; j < cols; j++)
            {
                if(DFS(matrix, rows, cols, str, i, j, pathLength, vis))
                {
                    delete vis;
                    return true;
                }
            }
        delete vis;
        return false;
    }
private:
    bool DFS(string matrix, int rows, int cols, string str, int row, int col, int pathLength, bool *vis)
    {
        if(str[pathLength] == '\0')
            return true;
        bool hasPath = false;
        if(row >= 0 && col >= 0 && row < rows && col < cols 
           && matrix[cols * row + col] == str[pathLength] 
           && !vis[cols * row + col])
        {
            pathLength++;
            vis[cols * row + col] = true;
            hasPath = DFS(matrix, rows, cols, str, row, col - 1, pathLength, vis) ||
                      DFS(matrix, rows, cols, str, row, col + 1, pathLength, vis) ||
                      DFS(matrix, rows, cols, str, row - 1, col, pathLength, vis) ||
                      DFS(matrix, rows, cols, str, row + 1, col, pathLength, vis);
            if(!hasPath)
            {
                pathLength--;
                vis[cols * row + col] = false;
            }
        }
        return hasPath;
    }
};
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值