|
| 1 | +// https://leetcode.com/problems/word-search |
| 2 | + |
| 3 | +public class Solution { |
| 4 | + public boolean helper(char[][]board, String word, boolean[][] visited, int r, int c) { |
| 5 | + if (word.length() == 0) { |
| 6 | + return true; |
| 7 | + } |
| 8 | + else { |
| 9 | + char nChar = word.charAt(0); |
| 10 | + visited[r][c] = true; |
| 11 | + if (r - 1 >= 0 |
| 12 | + && !visited[r-1][c] |
| 13 | + && board[r-1][c] == nChar |
| 14 | + && helper(board, word.substring(1, word.length()), visited, r-1, c)) { |
| 15 | + return true; |
| 16 | + } |
| 17 | + if (r + 1 < board.length |
| 18 | + && !visited[r+1][c] |
| 19 | + && board[r+1][c] == nChar |
| 20 | + && helper(board, word.substring(1, word.length()), visited, r+1, c)) { |
| 21 | + return true; |
| 22 | + } |
| 23 | + if (c - 1 >= 0 |
| 24 | + && !visited[r][c-1] |
| 25 | + && board[r][c-1] == nChar |
| 26 | + && helper(board, word.substring(1, word.length()), visited, r, c-1)) { |
| 27 | + return true; |
| 28 | + } |
| 29 | + if (c + 1 < board[r].length |
| 30 | + && !visited[r][c+1] |
| 31 | + && board[r][c+1] == nChar |
| 32 | + && helper(board, word.substring(1, word.length()), visited, r, c+1)) { |
| 33 | + return true; |
| 34 | + } |
| 35 | + visited[r][c] = false; |
| 36 | + |
| 37 | + return false; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + public boolean exist(char[][] board, String word) { |
| 42 | + boolean[][] visited = new boolean[board.length][board[0].length]; |
| 43 | + if (board.length * board[0].length >= word.length()) { |
| 44 | + for (int r = 0; r < board.length; r++) { |
| 45 | + for (int c = 0; c < board[r].length; c++) { |
| 46 | + if (board[r][c] == word.charAt(0)) { |
| 47 | + if(helper(board, word.substring(1, word.length()), visited, r, c)) |
| 48 | + return true; |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return false; |
| 55 | + } |
| 56 | +} |
0 commit comments