zoukankan      html  css  js  c++  java
  • [剑指Offer]12-矩阵中的路径(回溯)

    题目链接

    https://www.nowcoder.com/practice/c61c6999eecb4b8f88a98f66b273a3cc?tpId=13&tqId=11218&tPage=4&rp=4&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

    题目描述

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

    解题思路

    回溯法。

    相关知识

    二维数组做为形参传递必须指出第二维的维度,不论用传指针还是通过数组名传递的形式,如int (*A)[10]int a[][10],否则无法计算a+i*cols+j,即无法知道对应的内存地址。
    或者如代码中,用一维数组模拟二维数组,传参时传一维数组的指针即可,数组索引为i*cols+j

    代码

    class Solution {
    public:
        bool hasPath(char* matrix, int rows, int cols, char* str)
        {
            if(!matrix||!str){
                return false;
            }
            
            bool arrived[rows*cols+1];
            bool* pArrived=arrived;
            for(int i=0;i<rows;++i){
                for(int j=0;j<cols;++j){
                    arrived[i*cols+j]=true;
                }
            }
            
            for(int i=0;i<rows;++i){
                for(int j=0;j<cols;++j){
                    if(matched(matrix,rows,cols,i,j,str,0,pArrived)){
                        return true;
                    }
                }
            }
            return false;
        }
    private:
        bool matched(char* matrix,int rows,int cols,int i,int j,char* str,int pos,bool* pArrived){
            if(i<0||j<0||i>=rows||j>=cols||matrix[i*cols+j]!=str[pos]||!pArrived[i*cols+j]){
                return false;
            }
            if(pos==strlen(str)-1){
                return true;
            }
            pArrived[i*cols+j]=false;
            if(matched(matrix,rows,cols,i-1,j,str,pos+1,pArrived)||matched(matrix,rows,cols,i+1,j,str,pos+1,pArrived)||matched(matrix,rows,cols,i,j+1,str,pos+1,pArrived)||matched(matrix,rows,cols,i,j-1,str,pos+1,pArrived)){
                return true;
            }
            pArrived[i*cols+j]=true;
            return false;
        }
    };
    
  • 相关阅读:
    反向代理实例
    nginx常用命令和配置
    nginx的安装
    Can Live View boot up images acquired from 64bit OS evidence?
    What is the behavior of lnk files?
    EnCase v7 search hits in compound files?
    How to search compound files
    iOS 8.3 JB ready
    Sunglasses
    现代福尔摩斯
  • 原文地址:https://www.cnblogs.com/coding-gaga/p/10519795.html
Copyright © 2011-2022 走看看