矩阵中的路径

 

 1 class Solution {
 2     bool hasStr(char* matrix, int row, int rows, int col, int cols, char* str, vector<bool> &all)
 3     {
 4         if(*str == '\0')
 5             return true;
 6         if(col<0 || row<0)
 7             return false;
 8         if(row<rows && col<cols && all[row*cols+col]==false &&(*(matrix+row*cols+col)) == (*str))
 9         {
10             all[row*cols+col]=true;
11             if(hasStr(matrix, row-1, rows, col, cols, str+1,all)||
12                hasStr(matrix, row, rows, col+1, cols, str+1, all)||
13                hasStr(matrix, row+1, rows, col, cols, str+1, all)||
14                hasStr(matrix, row, rows, col-1, cols, str+1, all))
15                 return true;
16             else all[row*cols+col]=false;
17                 
18         }
19         return false;
20     }
21 public:
22     bool hasPath(char* matrix, int rows, int cols, char* str)
23     {
24         int row=0, col=0; 
25         vector<bool> all (rows*cols, false);
26         if( str==NULL || matrix==NULL ||*str=='\0' ||*matrix=='\0' || rows<1 ||cols<1)
27         return false;
28         for(; row<rows; ++row)
29         {
30             for(col=0; col<cols; ++col)
31             
32                 if(((*(matrix+row*cols+col)) == (*str)) && all[row*cols+col]==false)
33                 {
34                     if(true == hasStr(matrix, row, rows, col, cols, str, all) )
35                     return true;
36                 }
37             
38         }
39         return false;
40     }
41     
42 
43 };

 

posted on 2016-05-08 18:06  RenewDo  阅读(129)  评论(0编辑  收藏  举报

导航