11package com .thealgorithms .backtracking ;
22
3- /*
4- Word Search Problem (https://en.wikipedia.org/wiki/Word_search)
5-
6- Given an m x n grid of characters board and a string word, return true if word exists in the grid.
7-
8- The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are
9- those horizontally or vertically neighboring. The same letter cell may not be used more than once.
10-
11- For example,
12- Given board =
13-
14- [
15- ['A','B','C','E'],
16- ['S','F','C','S'],
17- ['A','D','E','E']
18- ]
19- word = "ABCCED", -> returns true,
20- word = "SEE", -> returns true,
21- word = "ABCB", -> returns false.
22- */
23-
24- /*
25- Solution
26- Depth First Search in matrix (as multiple sources possible) with backtracking
27- like finding cycle in a directed graph. Maintain a record of path
28-
29- Tx = O(m * n * 3^L): for each cell, we look at 3 options (not 4 as that one will be visited), we
30- do it L times Sx = O(L) : stack size is max L
31- */
32-
3+ /**
4+ * Word Search Problem
5+ *
6+ * This class solves the word search problem where given an m x n grid of characters (board)
7+ * and a target word, the task is to check if the word exists in the grid.
8+ * The word can be constructed from sequentially adjacent cells (horizontally or vertically),
9+ * and the same cell may not be used more than once in constructing the word.
10+ *
11+ * Example:
12+ * - For board =
13+ * [
14+ * ['A','B','C','E'],
15+ * ['S','F','C','S'],
16+ * ['A','D','E','E']
17+ * ]
18+ * and word = "ABCCED", -> returns true
19+ * and word = "SEE", -> returns true
20+ * and word = "ABCB", -> returns false
21+ *
22+ * Solution:
23+ * - Depth First Search (DFS) with backtracking is used to explore possible paths from any cell
24+ * matching the first letter of the word. DFS ensures that we search all valid paths, while
25+ * backtracking helps in reverting decisions when a path fails to lead to a solution.
26+ *
27+ * Time Complexity: O(m * n * 3^L)
28+ * - m = number of rows in the board
29+ * - n = number of columns in the board
30+ * - L = length of the word
31+ * - For each cell, we look at 3 possible directions (since we exclude the previously visited direction),
32+ * and we do this for L letters.
33+ *
34+ * Space Complexity: O(L)
35+ * - Stack space for the recursive DFS function, where L is the maximum depth of recursion (length of the word).
36+ */
3337public class WordSearch {
3438 private final int [] dx = {0 , 0 , 1 , -1 };
3539 private final int [] dy = {1 , -1 , 0 , 0 };
3640 private boolean [][] visited ;
3741 private char [][] board ;
3842 private String word ;
3943
44+ /**
45+ * Checks if the given (x, y) coordinates are valid positions in the board.
46+ *
47+ * @param x The row index.
48+ * @param y The column index.
49+ * @return True if the coordinates are within the bounds of the board; false otherwise.
50+ */
4051 private boolean isValid (int x , int y ) {
4152 return x >= 0 && x < board .length && y >= 0 && y < board [0 ].length ;
4253 }
4354
55+ /**
56+ * Performs Depth First Search (DFS) from the cell (x, y)
57+ * to search for the next character in the word.
58+ *
59+ * @param x The current row index.
60+ * @param y The current column index.
61+ * @param nextIdx The index of the next character in the word to be matched.
62+ * @return True if a valid path is found to match the remaining characters of the word; false otherwise.
63+ */
4464 private boolean doDFS (int x , int y , int nextIdx ) {
4565 visited [x ][y ] = true ;
4666 if (nextIdx == word .length ()) {
4767 return true ;
4868 }
69+
4970 for (int i = 0 ; i < 4 ; ++i ) {
5071 int xi = x + dx [i ];
5172 int yi = y + dy [i ];
@@ -56,10 +77,19 @@ private boolean doDFS(int x, int y, int nextIdx) {
5677 }
5778 }
5879 }
59- visited [x ][y ] = false ;
80+
81+ visited [x ][y ] = false ; // Backtrack
6082 return false ;
6183 }
6284
85+ /**
86+ * Main function to check if the word exists in the board. It initiates DFS from any
87+ * cell that matches the first character of the word.
88+ *
89+ * @param board The 2D grid of characters (the board).
90+ * @param word The target word to search for in the board.
91+ * @return True if the word exists in the board; false otherwise.
92+ */
6393 public boolean exist (char [][] board , String word ) {
6494 this .board = board ;
6595 this .word = word ;
0 commit comments