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
| public boolean exist(char[][] board, String word) { int row = board.length; int col = board[0].length;
if (row == 0) { return false; }
boolean[][] visited = new boolean[row][col];
for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (dfs(board, visited, i, j, word, 0)) { return true; } } }
return false; }
private boolean dfs(char[][] board, boolean[][] visited, int row, int col, String word, int charIndex) { if (row < 0 || row >= board.length || col < 0 || col >= board[0].length) { return false; }
if (visited[row][col] || word.charAt(charIndex) != board[row][col]) { return false; }
if (charIndex == word.length() - 1) { return true; }
visited[row][col] = true;
boolean up = dfs(board, visited, row - 1, col, word, charIndex + 1); if (up) { return true; }
boolean down = dfs(board, visited, row + 1, col, word, charIndex + 1); if (down) { return true; }
boolean left = dfs(board, visited, row , col - 1, word, charIndex + 1); if (left) { return true; }
boolean right = dfs(board, visited, row, col + 1, word, charIndex + 1); if (right) { return true; }
visited[row][col] = false; return false; }
|