|
| 1 | +/** |
| 2 | + * Created by PRADHANG on 4/13/2017. |
| 3 | + * Accepted |
| 4 | + */ |
| 5 | +public class WordSearch |
| 6 | +{ |
| 7 | + private static final int[] R = {0,0,1,-1}; |
| 8 | + private static final int[] C = {1,-1,0,0}; |
| 9 | + private static boolean[][] visited; |
| 10 | + private static int length = 0, N, M; |
| 11 | + /** |
| 12 | + * Main method |
| 13 | + * @param args |
| 14 | + * @throws Exception |
| 15 | + */ |
| 16 | + public static void main(String[] args) throws Exception |
| 17 | + { |
| 18 | + char[][] board = { |
| 19 | + {'A'} |
| 20 | + }; |
| 21 | + System.out.println(new WordSearch().exist(board, "A")); |
| 22 | + } |
| 23 | + |
| 24 | + public boolean exist(char[][] board, String word) |
| 25 | + { |
| 26 | + N = board.length; |
| 27 | + M = board[0].length; |
| 28 | + if(N * M < word.length()) return false; |
| 29 | + visited = new boolean[N][M]; |
| 30 | + length = word.length(); |
| 31 | + for (int i = 0 ; i < N; i ++) |
| 32 | + { |
| 33 | + for (int j = 0 ; j < M; j ++) |
| 34 | + { |
| 35 | + if(board[i][j] == word.charAt(0)) |
| 36 | + { |
| 37 | + if(dfs(i, j, board, word, 1)) return true; |
| 38 | + visited[i][j] = false; |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + return false; |
| 43 | + } |
| 44 | + |
| 45 | + private boolean dfs(int r, int c, char[][] board, String word, int pos) |
| 46 | + { |
| 47 | + if(pos < length) |
| 48 | + { |
| 49 | + visited[r][c] = true; |
| 50 | + for(int i = 0; i < 4; i ++) |
| 51 | + { |
| 52 | + int newR = r + R[i]; |
| 53 | + int newC = c + C[i]; |
| 54 | + if(newR >= 0 && newR < N && newC >= 0 && newC < M) |
| 55 | + { |
| 56 | + if(!visited[newR][newC]) |
| 57 | + { |
| 58 | + if(board[newR][newC] == word.charAt(pos)) |
| 59 | + { |
| 60 | + if(dfs(newR, newC, board, word, pos + 1)) return true; |
| 61 | + visited[newR][newC] = false; |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + else return true; |
| 68 | + return false; |
| 69 | + } |
| 70 | +} |
0 commit comments