JZ12_矩阵中的路径

JZ12 矩阵中的路径

描述

请设计一个函数,用来判断在一个n乘m的矩阵中是否存在一条包含某长度为len的字符串所有字符的路径。

路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如

1
2
3
[ a b c e 
s f c s
a d e e ]

矩阵中包含一条字符串$”bcced”$的路径,但是矩阵中不包含$”abcb”$路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

数据范围:$0≤n,m≤20 $,$1≤len≤25 $

示例1

1
2
输入:[[a,b,c,e],[s,f,c,s],[a,d,e,e]],"abcced"
返回值:true

示例2

1
2
输入:[[a,b,c,e],[s,f,c,s],[a,d,e,e]],"abcb"
返回值:false
1
2
0 <= matrix.length <= 200
0 <= matrix[i].length <= 200

题解

前面在写其它算法的时候,不管是二叉树还是动态规划,对回溯的算法都还是有一些模糊,这一次终于是弄了个清楚明白。

回溯的特征就是在于,做出选择,尝试探索,重置选择

对于这道题来说,因为可以从任意位置作为起点开始探索,所以要额外增加一步寻找起点的过程,直接遍历整个二维数组即可。然后是开始写回溯算法的部分,首先确定递归的返回条件,当已经找完了$word$则成功,若当前我们比对的$word[index]$与$matrix[i][j]$不匹配时,自然是失败了。

然后开始写递归的处理部分:首先是做出选择,我们假定选择了$matrix[i][j]$,就把它设置为$’#‘$;第二步尝试探索,则是尝试探索它上下左右的四个方向,这里要注意写好边界判断,不要让数组越界;最后重置选择,探索完了以后再回来把$matrix[i][j]$设置回原来的字符,最后这四个只要有一个方向返回的是$true$,即探索成功。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param matrix char字符型vector<vector<>>
* @param word string字符串
* @return bool布尔型
*/
bool hasPath(vector<vector<char> >& matrix, string word) {
if (matrix[0].empty()) return false;


//确定起点
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[0].size(); j++) {
if (word[0] == matrix[i][j]) {
if (findPath(matrix, i, j, word, 0)) return true;
}
}
}
return false;
}

private:
bool findPath(vector<vector<char>>& matrix, int start_i, int start_j,
string word, int index) {
if (matrix[start_i][start_j] != word[index]) return false; // 核心检查
if (index == word.length() - 1) return true;

char temp = matrix[start_i][start_j];
matrix[start_i][start_j] = '#'; // 标记已访问

bool found = false;
if (start_i > 0) found = found ||
findPath(matrix, start_i - 1, start_j, word, index + 1);
if (start_i < matrix.size() - 1) found = found ||
findPath(matrix, start_i + 1, start_j, word, index + 1);
if (start_j > 0) found = found ||
findPath(matrix, start_i, start_j - 1, word, index + 1);
if (start_j < matrix[0].size() - 1) found = found ||
findPath(matrix, start_i, start_j + 1, word, index + 1);

matrix[start_i][start_j] = temp; // 回溯

return found;
}

};