Path Matrix

1 backtracking

class Solution {
 public :
     BOOL hasPath ( char * Matrix, int rows, int cols, char * STR) 
    { 
     IF (STR Matrix == == NULL NULL || || rows <= 0 || cols <= 0 )
          return  to false ;
      int Row = 0 ;
      int COL = 0 ;
      BOOL * = visited new new  BOOL [rows cols *];   // new new a matrix, returns a pointer; for detecting whether a node of each; 
     Memset (visited, 0 , rows *cols);
      int pathLength = 0 ; // the string located 
     for (Row = 0 ; Row <rows; Row ++ ) 
       { 
          for (COL = 0 ; COL <cols; COL ++ ) 
          { 
             IF (hasPathCore (Matrix, rows, cols , Row, COL, STR, visited, pathLength)) // if the path search is successful 
             {
                return   to true ; 
             } 
          } 
       } 
       Delete [] visited;
        return   to false ; 
    } 
  public : 
       BOOL hasPathCore (char * Matrix, int rows, int cols, int Row, int COL, char * STR, BOOL * visited, int & pathLength) 
     { 
      BOOL haspath = to false ;
       // pointer words above have verified a non-null pointer the   
      IF (STR [ pathLength] == ' \ 0 ' ) // If a null character is at a position   
      {
          return  to true ; 
      } 
      // need to be limiting in each function Lane                                                  // not accessed 
      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 (the Matrix, rows, cols, Row, COL + 1 , str, visited, pathLength));
          IF ! (haspath) // If the path is not found, then   // we rollback 
         { 
          pathLength -; // rollback a 
          visited [COL + Row * cols] = false ; // when I have not visited here 
         } 

      
      } 
         return haspath; 
  } 


};

 

Guess you like

Origin www.cnblogs.com/cgy1012/p/11373329.html