文章524
标签277
分类67

算法:矩阵中的路径


矩阵中的路径

矩阵中的路径

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。

例如矩阵

[a b c e]

[s f c s]

[a d e e]

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


分析

明显的四个方向的DFS + 回溯法;


代码

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
public class Solution {
private boolean[] visited;

private int level;

public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
visited = new boolean[rows * cols];

for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
level = 0;
if (helper(matrix, rows, cols, str, i, j)) {
return true;
}
}
}
return false;
}

private boolean helper(char[] matrix, int rows, int cols, char[] str, int curRow, int curCol) {
if (curRow < 0 || curRow >= rows || curCol < 0 || curCol >= cols
|| visited[curRow * cols + curCol]
|| matrix[curRow * cols + curCol] != str[level]) return false;

level++;
visited[curRow * cols + curCol] = true;
if (level == str.length) return true;

boolean flag = false;
flag = helper(matrix, rows, cols, str, curRow + 1, curCol)
|| helper(matrix, rows, cols, str, curRow, curCol + 1)
|| helper(matrix, rows, cols, str, curRow - 1, curCol)
|| helper(matrix, rows, cols, str, curRow, curCol - 1);

if (!flag) {
level--;
visited[curRow * cols + curCol] = false;
}
return flag;
}
}

本文作者:Jasonkay
本文链接:https://jasonkayzk.github.io/cn/1996/07/27/%E7%AE%97%E6%B3%95-%E7%9F%A9%E9%98%B5%E4%B8%AD%E7%9A%84%E8%B7%AF%E5%BE%84/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可