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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| public class CodingInterview_012 { public static boolean hasPath(char[] matrix, int rows, int cols, char[] str) { if (matrix == null || matrix.length != rows * cols || str == null || str.length < 1) { return false; }
boolean[] visited = new boolean[rows * cols]; for (int i = 0; i < visited.length; i++) { visited[i] = false; }
int pathLength = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (hasPathCore(matrix, rows, cols, str, visited, i, j, pathLength)) { return true; } } }
return false; }
private static boolean hasPathCore(char[] matrix, int rows, int cols, char[] str, boolean[] visited, int row, int col, int pathLength) {
if (pathLength == str.length) { return true; }
boolean hasPath = false;
if (row >= 0 && row < rows && col >= 0 && col < cols && matrix[row * cols + col] == str[pathLength] && !visited[row * cols + col]) { visited[row * cols + col] = true; pathLength++;
hasPath = hasPathCore(matrix, rows, cols, str, visited, row, col - 1, pathLength) || hasPathCore(matrix, rows, cols, str, visited, row - 1, col, pathLength) || hasPathCore(matrix, rows, cols, str, visited, row, col + 1, pathLength) || hasPathCore(matrix, rows, cols, str, visited, row + 1, col, pathLength);
if (!hasPath) { pathLength--; visited[row * cols + col] = false; }
}
return hasPath; }
}
|