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; } }
|