题目
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。
思想
递归
代码
import java.util.*;
public class Solution {
int rows, cols;
boolean flag;
boolean[] isVisted;
int[] dx = new int[]{-1, 0, 1, 0};
int[] dy = new int[]{0, 1, 0, -1};
public boolean hasPath(String matrix, int rows, int cols, String str) {
// write code here
if (matrix.length() < str.length()) {
return false;
}
flag = false;
this.rows = rows;
this.cols = cols;
isVisted = new boolean[matrix.length()];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
dfs(matrix, i, j, str, 0);
if (flag) {
return true;
}
}
}
return false;
}
private void dfs(String matrix, int i, int j, String str, int p) {
int pos = i * cols + j;
if (i < 0 || j < 0 || i >= rows || j >= cols
|| isVisted[pos] || matrix.charAt(pos) != str.charAt(p)) {
return;
}
if (p == str.length() - 1) {
flag = true;
return;
}
isVisted[pos] = true;
for (int k = 0; k < 4; k++) {
int nx = i + dx[k];
int ny = j + dy[k];
dfs(matrix, nx, ny, str, p + 1);
if (flag) {
return;
}
}
isVisted[pos] = false;
}
}