路径是否包含指定字符串
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径
路径可以从矩阵中任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格,如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子
分析
当矩阵中坐标为(row,column)
的格子和路径字符串中下标为index
的字符一样时,从4个相邻的格子(row,column-1)、(row,column+1)、(row-1,column)、(row+1,column)
中去定位路径字符串中下标为index+1
的字符
如果4个相邻的格子都没有匹配字符串中下标为index+1
的字符,表明当前路径字符串中下标为index
的字符在矩阵中的定位不正确,index--
,然后重新定位
public class StringPathInMatrix {
public boolean hasPath(char[][] matrix, String str) {
if (Optional.ofNullable(matrix).isEmpty()
|| matrix.length <= 0 || matrix[0].length <= 0
|| Optional.ofNullable(str).isEmpty()
|| str.length() <= 0) {
return false;
}
return hasPath(matrix, matrix.length,
matrix[0].length, str.toCharArray());
}
private boolean[][] init(int rows, int columns) {
boolean[][] visited = new boolean[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
visited[i][j] = false;
}
}
return visited;
}
private boolean hasPath(char[][] matrix, int rows, int columns, char[] str) {
int index = 0;
boolean[][] visited = init(rows, columns);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (hasPathCore(matrix, rows, columns,
i, j, str, index, visited)) {
return true;
}
}
}
return false;
}
private boolean hasPathCore(char[][] matrix, int rows, int columns,
int row, int column, char[] str,
int index, boolean[][] visited) {
if (index >= str.length) {
return true;
}
boolean hasPath = false;
if (row >= 0 && row < rows && column >= 0 && column < columns
&& matrix[row][column] == str[index] && !visited[row][column]) {
++index;
visited[row][column] = true;
hasPath = hasPathCore(matrix, rows, columns,
row, column - 1, str, index, visited)
|| hasPathCore(matrix, rows, columns,
row, column + 1, str, index, visited)
|| hasPathCore(matrix, rows, columns,
row - 1, column, str, index, visited)
|| hasPathCore(matrix, rows, columns,
row + 1, column, str, index, visited);
if (!hasPath) {
--index;
visited[row][column] = false;
}
}
return hasPath;
}
public static void main(String[] args) {
StringPathInMatrix inMatrix = new StringPathInMatrix();
char[][] matrix = new char[][]{
{'a', 'b', 'c', 'e'},
{'s', 'f', 'c', 's'},
{'a', 'd', 'e', 'e'}};
String[] strs = new String[]{"bcced", "abcb", "abccfdees", "abccfdeesc"};
for (String str : strs) {
boolean result = inMatrix.hasPath(matrix, str);
System.out.println(result);
}
}
}
网友评论