|
| 1 | +package com.thealgorithm.backtracking; |
| 2 | + |
| 3 | +/** |
| 4 | + * @author: Subham Santra |
| 5 | + */ |
| 6 | +public class WordSearch { |
| 7 | + public boolean exist(char[][] board, String word) { |
| 8 | + final int m = board.length; |
| 9 | + final int n = board[0].length; |
| 10 | + final boolean[][] taken = new boolean[m][n]; |
| 11 | + |
| 12 | + for (int i = 0; i < m; ++i) { |
| 13 | + for (int j = 0; j < n; ++j) { |
| 14 | + if (board[i][j] == word.charAt(0)) { |
| 15 | + if (EXPLORE(board, i, j, m, n, 0, word, taken)) { |
| 16 | + return true; |
| 17 | + } |
| 18 | + } |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + return false; |
| 23 | + } |
| 24 | + |
| 25 | + boolean EXPLORE( |
| 26 | + char[][] board, |
| 27 | + int i, |
| 28 | + int j, |
| 29 | + int m, |
| 30 | + int n, |
| 31 | + int wordCharIndex, |
| 32 | + String word, |
| 33 | + boolean[][] taken) { |
| 34 | + if (wordCharIndex == word.length()) { |
| 35 | + return true; |
| 36 | + } |
| 37 | + |
| 38 | + if (!((0 <= i && i < m) && (0 <= j && j < n))) { |
| 39 | + return false; |
| 40 | + } |
| 41 | + |
| 42 | + if (taken[i][j]) { |
| 43 | + return false; |
| 44 | + } |
| 45 | + |
| 46 | + boolean ans = false; |
| 47 | + |
| 48 | + taken[i][j] = true; |
| 49 | + if (board[i][j] == word.charAt(wordCharIndex)) { |
| 50 | + // We will explore further |
| 51 | + ans |= EXPLORE(board, i, j + 1, m, n, wordCharIndex + 1, word, taken); |
| 52 | + ans |= EXPLORE(board, i, j - 1, m, n, wordCharIndex + 1, word, taken); |
| 53 | + ans |= EXPLORE(board, i + 1, j, m, n, wordCharIndex + 1, word, taken); |
| 54 | + ans |= EXPLORE(board, i - 1, j, m, n, wordCharIndex + 1, word, taken); |
| 55 | + } |
| 56 | + taken[i][j] = false; |
| 57 | + return ans; |
| 58 | + } |
| 59 | + |
| 60 | + public static void main(String[] args) { |
| 61 | + char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}}; |
| 62 | + System.out.println(new WordSearch().exist(board, "ABCCED")); |
| 63 | + System.out.println(new WordSearch().exist(board, "ABCF")); |
| 64 | + System.out.println(new WordSearch().exist(board, "SEE")); |
| 65 | + } |
| 66 | +} |
0 commit comments