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
| class Solution { private static final int[][] DIRECTIONS = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public boolean exist(char[][] board, String word) { int m = board.length, n = board[0].length;
for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (dfs(board, i, j, word, 0)) { return true; } } }
return false; }
private boolean dfs(char[][] board, int i, int j, String word, int index) { int m = board.length, n = board[0].length;
if (index == word.length() - 1) { if (board[i][j] == word.charAt(index)) { return true; } else { return false; } }
if (board[i][j] == word.charAt(index)) { char c = board[i][j]; board[i][j] = '*'; for (int[] direction : DIRECTIONS) { int nextI = i + direction[0], nextJ = j + direction[1]; if (nextI >= 0 && nextI < m && nextJ >= 0 && nextJ < n) { if (dfs(board, nextI, nextJ, word, index + 1)) { return true; } } } board[i][j] = c; }
return false; } }
|