_Swordfinger offer series 54: Paths in matrices

Keywords: PHP REST

This topic uses the retrospective method.

The retrospective method was seldom practiced before, so this problem still needs to be paid attention to.

The backtracking method is learned in the algorithm, which starts with the first possible path and finds the last one.

A few points should be paid attention to in this topic:

1. Starting from the first, if the first element equals the first element of the string to be searched for, continue to search for the upper and lower parts of the element to see if it equals the next one. Match to the last element.

2. If the next element can't be found in its top or bottom, go back to the upper level, indicating that the element may have gone wrong.

3. Because access paths cannot be accessed again, a bool variable of the same size is created to record whether the current location has passed.

 1 class Solution {
 2 public:
 3     bool hasPath(char* matrix, int rows, int cols, char* str)
 4     {
 5         if (matrix == NULL || rows <= 0 || cols <= 0 || str == NULL)
 6             return false;
 7 
 8         bool* visited = new bool[rows*cols];//Define a variable the same size as a matrix to record whether each location has been accessed
 9         memset(visited, 0, rows*cols);
10 
11         int index = 0;
12         for(int i=0;i<rows;i++)
13             for (int j = 0; j < cols; j++)
14             {
15                 if (hasPathcore(matrix, rows, cols, i, j,str, index, visited))
16                     return true;
17             }
18         delete[]visited;
19         return false;
20     }
21     bool hasPathcore(char* matrix, int rows, int cols, int row,int col,char* str,int index,bool *visit)
22     {
23         if (str[index] == '\0')//Recursive termination conditions, until the end
24             return true;
25         bool has=false;
26         if (row <= rows&&col <= cols&&matrix[row*cols + col] == str[index] && !visit[row*cols + col])
27         {
28             visit[row*cols + col] = true;
29             index++;
30             //Find the rest of the string
31             has = hasPathcore(matrix, rows, cols, row, col+1, str, index, visit)//right
32                 || hasPathcore(matrix, rows, cols, row+1, col, str, index, visit)//lower
33                 || hasPathcore(matrix, rows, cols, row, col-1, str, index, visit)//Left
34                 || hasPathcore(matrix, rows, cols, row-1, col, str, index, visit);//upper
35 
36             if (!has)//Neither the top nor the bottom found the next element, indicating that the element went wrong and went back to the previous step.
37             {
38                 index--;
39                 visit[row*cols + col] = false;
40             }
41         }
42     
43         return has;
44     }
45 
46 
47 };

Posted by PHPFreaksMaster on Wed, 31 Jul 2019 09:11:57 -0700