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
| class Solution { public boolean exist(char[][] board, String word) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (backtrack(board, word, i, j, 0)) { return true; } } } return false; }
boolean backtrack(char[][] board, String word, int x, int y, int start) { if (x >= board.length || x < 0 || y >= board[0].length || y < 0 || board[x][y] != word.charAt(start)) { return false; } if (start == word.length() - 1) { return true; }
char temp = board[x][y]; board[x][y] = '#'; boolean result = backtrack(board, word, x + 1, y, start + 1) || backtrack(board, word, x - 1, y, start + 1) || backtrack(board, word, x, y + 1, start + 1) || backtrack(board, word, x, y - 1, start + 1); board[x][y] = temp; return result; } }
|