矩阵中的路径

10 篇文章 0 订阅
9 篇文章 1 订阅

题目描述

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 3×4 矩阵
 a     b   c    e 
 s     f    c    s 
  a    d    e    e 
中包含一条字符串 "bcced" 的路径,但是矩阵中不包含 "abcb" 路径,因为字符串的第一个字符 b 占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
解题思路
用回溯法解!
假设矩阵为 matrix,字符串为 str,定义一个与矩阵等大小的 bool 矩阵 isVisited 用于标记格子是否被访问。
1. 当在矩阵 matrix 中找到一个匹配字符串 str 的 index 处字符的格子,标记此格子为已访问。
2. 从该格子开始沿四个方向递归查找下一个格子匹配 str 的 index 处的下一个字符。
1) 若找到,则继续递归匹配下一个字符,以此递归直到匹配到 str 的末尾,或者匹配不到了。
2) 若找不到,则回溯,重新选择下一个和 index 处匹配的格子。
C++ 代码:
bool hasPath(char* matrix, int rows, int cols, char* str, int r, int c, int& index, bool* isVisited) {
    if('\0' == str[index])// 如果到了字符串 str 的末尾, 则表示矩阵中存在一个路径
        return true;
    bool isHasPath = false;
    // 如果坐标 <r, c> 处的格子匹配字符串 str 的 index 处的字符,则朝四个方向递归查找下一个匹配的字符
    if(r >= 0 && r < rows && c >= 0 && c < cols &&
            matrix[r*cols+c] == str[index] && !isVisited[r*cols+c]) {
        index++;
        isVisited[r*cols+c] = true;// 标记坐标 <r, c> 处的格子为已访问
        isHasPath = hasPath(matrix, rows, cols, str, r, c+1, index, isVisited) ||// 朝右找
                    hasPath(matrix, rows, cols, str, r+1, c, index, isVisited) ||// 朝下找
                    hasPath(matrix, rows, cols, str, r, c-1, index, isVisited) ||// 朝左找
                    hasPath(matrix, rows, cols, str, r-1, c, index, isVisited);// 朝上找
        if(!isHasPath) {// 如果无法找到下一个匹配的格子,则回溯,重新选择和当前字符匹配的格子
            index--;
            isVisited[r*cols+c] = false;
        }
    }
    return isHasPath;
}

bool HasPath(char* matrix, int rows, int cols, char* str) {// 【矩阵中的路径(回溯法解决)】
    if(NULL == matrix || NULL == str || cols <= 0 || cols <= 0)
        return false;
    bool *isVisited = new bool[rows * cols]();// 用来标记格子是否被访问过,初始化全为 0,即 false
    int index = 0;
    for(int r=0; r < rows; r++)
        for(int c=0; c < cols; c++)
            if(hasPath(matrix, rows, cols, str, r, c, index, isVisited)) {
                delete[] isVisited;
                return true;
            }
    delete[] isVisited;
    return false;
}




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值