剑指offer-矩阵中的路径

题目 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。

思路
回溯法:用回溯法解决问题就是,在某一步选择了其中一个选项,就进入了下一步,然后又面临新的选项,就这样递归的进行下去,当某条路走不通时,就退回一步。

代码

bool hasPath(char*matrix,int rows,int cols,char*str)
{
   if(matrix==NULL||rows<0||cols<0||str==NULL)
   {
       return false;
   }


    int strindex=0;//标记已经遍历到str的哪个字符了

     //定义一个标记矩阵,标记这个点是否已经访问过
    int*visited=new int[rows*cols];//尽量使用一维的
    for(int i=0;i<rows;i++)
    {
        for(int j=0;j<cols;j++)
        {
            visited[i*cols+j]=0;
        }
    }
    for(int row=0;row<rows;row++)
    {
        for(int col=0;col<cols;col++)
        {
           if(hasPathCore(matrix,rows,cols,row,col,str,visited,strindex))
            return true;
        }
    }
    delete []visited;
    return false;

}
bool hasPathCore(char*matrix,int rows,int cols,int row,int col,char*str,int*visited,int strindex)
{
    if(str[strindex]=='\0')
        return true;

   //定义好进行递归所需要满足的条件
   if(matrix[row*cols+col]==str[strindex]&&0<=row&&row<rows&&0<=col&&col<cols&&visited[row*cols+col]!=1)
    {
        strindex++;
        visited[row][col]==1;
      //去上下左右找
        if(hasPathCore(matrix,rows,cols,row,col-1,str,visited,strindex)
          ||hasPathCore(matrix,rows,cols,row-1,col,str,visited,strindex)||
          hasPathCore(matrix,rows,cols,row,col+1,str,visited,strindex)
          ||hasPathCore(matrix,rows,cols,row+1,col,str,visited,strindex))
        return true;
        //如果没找到,则返回一格
        else{
            --strindex;
            visited[row*cols+col]=0;
        }
    }
    return false;
}

猜你喜欢

转载自blog.csdn.net/gary_god/article/details/79898005