矩阵的路径

1回溯法

class Solution {
public:
    bool hasPath(char* matrix, int rows, int cols, char* str)
    {
     if( matrix==NULL||str==NULL||rows<=0||cols<=0)
         return false;
     int row=0;
     int col=0;
     bool * visited=new bool[rows*cols];  //new 一个矩阵,返回一个指针;用以检测每个节点是否经过了的;
     memset(visited,0,rows*cols);
     int pathlength=0;//字符串所在的位置
     for(row=0;row<rows;row++)
       {
          for(col=0;col<cols;col++)
          {
             if(hasPathCore(matrix,rows,cols,row,col,str,visited,pathlength))//如果路径搜索成功
             {
               return  true; 
             }
          }
       }
       delete [] visited;
       return  false; 
    }
  public : 
      bool hasPathCore(char* matrix,int rows, int cols, int row, int col, char* str, bool * visited,int & pathlength)
     {
      bool haspath=false;
      //指针的话上面已经验证过非空指针了  
      if(str[pathlength]=='')//如果位置处是空字符  
      {
         return true; 
      }
      //有必要在每个函数里进行限制                                                 //没有被访问过
      if(row>=0&&row<rows&&col>=0&&col<cols&&matrix[col+row*cols]==str[pathlength]&&visited[col+row*cols]==false)
      {
         pathlength++; //先向前走
         visited[col+row*cols]=true;
        //围绕该点的上下左右找 看有无和path相对应的值
          haspath= (hasPathCore(matrix,rows,cols,row-1,col,str,visited,pathlength)||       
                   hasPathCore(matrix,rows,cols,row+1,col,str,visited,pathlength)||
                   hasPathCore(matrix,rows,cols,row,col-1,str,visited,pathlength)||
                   hasPathCore(matrix,rows,cols,row,col+1,str,visited,pathlength));
         if(!haspath)//如果该路径没找到的话  //那么我们回退
         {
          pathlength--;//回退一个
          visited[col+row*cols]=false; //当我没参观过此处
         }

      
      }
         return haspath;
  }


};
原文地址:https://www.cnblogs.com/cgy1012/p/11373329.html