今天下班回到住的地方还算早,九点多一丢丢就到住的地方了,然后趁机洗了个香香,整个人神清气爽。
然后打开电脑,想着还是写一道题吧,那就剑指offer从昨天的地方接着看吧。OK,第12题,是一道回溯法相关的题,一般也都是用dfs深度优先遍历来解题的。
题目描述:
代码:
public class Design {
public static boolean hasPath(char[][] matrix, String str) {
int len = matrix.length;
int width = matrix[0].length;
if (len == 0 || str == null || str.length() == 0) {
return false;
}
boolean[][] visited = new boolean[len][width];
for (int i = 0; i < len; i++) {
for (int j = 0; j < width; j++) {
boolean dfsRes = dfs(matrix, i, j, str, 0, visited);
if (dfsRes) {
return true;
}
}
}
return false;
}
private static boolean dfs(char[][] matrix, int x, int y, String str, int index, boolean[][] visited) {
if (matrix[x][y] == str.charAt(index)) {
visited[x][y] = true;
} else {
return false;
}
if (index == str.length() - 1) {
return true;
}
boolean first = false, second = false, third = false, fourth = false;
// 向上
if (x - 1 >= 0 && !visited[x - 1][y]) {
first = dfs(matrix, x - 1, y, str, index + 1, visited);
}
// 向左
if (y - 1 >= 0 && !visited[x][y - 1]) {
second = dfs(matrix, x, y - 1, str, index + 1, visited);
}
// 向右
if (y + 1 < matrix[0].length && !visited[x][y + 1]) {
third = dfs(matrix, x, y + 1, str, index + 1, visited);
}
// 向下
if (x + 1 < matrix.length && !visited[x + 1][y]) {
fourth = dfs(matrix, x + 1, y, str, index + 1, visited);
}
visited[x][y] = false;
return first || second || third || fourth;
}
public static void main(String[] args) {
char[][] maxtrix =
{{'a', 'b', 't', 'g'},
{'c', 'f', 'c', 's'},
{'j', 'd', 'e', 'h'}};
String str = "hscfcd";
System.out.println(hasPath(maxtrix, str));
}
}
提醒:
visited[x][y] = false;
很关键,不要忘记了这行代码
如果不加这行代码,用下面的例子就会出错
public static void main(String[] args) {
char[][] maxtrix =
{{'a', 'b', 'f', '#', '@'},
{'b', 'f', 'q', 'e', '@'},
{'f', '#', '*', '~', '#'}};
String str = "abf#*~#@@#";
System.out.println(hasPath(maxtrix, str));
}