面试题66 矩阵中的路径

题目描述

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
 1 class Solution {
 2 public:
 3     bool path(char* matrix, int rows, int cols, char* str, int i, int j, vector<int> isWalked){
 4         if (matrix[i * cols + j] == str[0] && isWalked[i * cols + j] == 0){
 5             if (*(str+1) == '')
 6                 return true;
 7             isWalked[i * cols + j] = 1;
 8             bool result = false;
 9             if (i - 1 >= 0)
10                 result = path(matrix, rows, cols, str + 1, i - 1, j, isWalked);
11             if (!result && i + 1 < rows)
12                 result = path(matrix, rows, cols, str + 1, i + 1, j, isWalked);
13             if (!result && j - 1 >= 0)
14                 result = path(matrix, rows, cols, str + 1, i, j - 1, isWalked);
15             if (!result && j + 1 < cols)
16                 result = path(matrix, rows, cols, str + 1, i, j + 1, isWalked);
17             return result;
18         }
19         else
20             return false;
21     }
22     bool hasPath(char* matrix, int rows, int cols, char* str)
23     {
24         if (str == NULL)
25             return false;
26         if (*str == '')
27             return true;
28         vector<int> isWalked;
29         for (int i = 0; i < rows * cols; i++)
30             isWalked.push_back(0);
31         for (int i = 0; i < rows; i++){
32             for (int j = 0; j < cols; j++){
33                 if (path(matrix, rows, cols, str, i, j, isWalked))
34                     return true;
35             }
36         }
37         return false;
38     }
39 };
原文地址:https://www.cnblogs.com/wanderingzj/p/5375765.html