zoukankan      html  css  js  c++  java
  • 矩阵中的路径

    题目描述

    请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
     
    思路:
    这题和机器人那题类似,只是出发点不再是(0,0)了,其他想法类似,代码如下:
    class Solution {
    public:
        bool hasFun(char* matrix, int rows, int cols, char* str,int x,int y,bool * flags,int pos)
        {
            if(pos==strlen(str))
            {
                return true;
            }
            if(x>=rows||y>=cols||x<0||y<0)
                return false;
            if(flags[x*cols+y])
                return false;
            if(matrix[x*cols+y]==str[pos])
            {
                flags[x*cols+y]=true;
                bool fc=hasFun(matrix,rows,cols,str,x-1,y,flags,pos+1)||hasFun(matrix,rows,cols,str,x+1,y,flags,pos+1)||hasFun(matrix,rows,cols,str,x,y-1,flags,pos+1)||hasFun(matrix,rows,cols,str,x,y+1,flags,pos+1);
                return fc;
            }
            else
                return false;
        }
        bool hasPath(char* matrix, int rows, int cols, char* str)
        {
            for(int x=0;x<rows;x++)
            {
                for(int y=0;y<cols;y++)
                {
                    if(matrix[x*cols+y]==str[0])
                    {
                        bool * flags=new bool[rows*cols];
                        for(int i=0;i<rows*cols;i++)
                        {
                            flags[i]=false;
                        }
                        if(hasFun(matrix,rows,cols,str,x,y,flags,0))
                            return true;
                    }
                }
            }
            return false;
        }
    
    
    };
  • 相关阅读:
    python之路面向对象2
    [C#]扩展方法
    [UGUI]Text文字效果
    [UGUI]修改顶点
    [UGUI]帧动画
    [UGUI]图文混排(二):Text源码分析
    [UGUI]图文混排(一):标签制定和解析
    [Unity基础]镜头管理类
    [Unity工具]批量修改Texture
    323 XAMPP软件
  • 原文地址:https://www.cnblogs.com/JsonZhangAA/p/12157303.html
Copyright © 2011-2022 走看看