1
1
package com .thealgorithms .backtracking ;
2
2
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
+ */
33
37
public class WordSearch {
34
38
private final int [] dx = {0 , 0 , 1 , -1 };
35
39
private final int [] dy = {1 , -1 , 0 , 0 };
36
40
private boolean [][] visited ;
37
41
private char [][] board ;
38
42
private String word ;
39
43
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
+ */
40
51
private boolean isValid (int x , int y ) {
41
52
return x >= 0 && x < board .length && y >= 0 && y < board [0 ].length ;
42
53
}
43
54
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
+ */
44
64
private boolean doDFS (int x , int y , int nextIdx ) {
45
65
visited [x ][y ] = true ;
46
66
if (nextIdx == word .length ()) {
47
67
return true ;
48
68
}
69
+
49
70
for (int i = 0 ; i < 4 ; ++i ) {
50
71
int xi = x + dx [i ];
51
72
int yi = y + dy [i ];
@@ -56,10 +77,19 @@ private boolean doDFS(int x, int y, int nextIdx) {
56
77
}
57
78
}
58
79
}
59
- visited [x ][y ] = false ;
80
+
81
+ visited [x ][y ] = false ; // Backtrack
60
82
return false ;
61
83
}
62
84
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
+ */
63
93
public boolean exist (char [][] board , String word ) {
64
94
this .board = board ;
65
95
this .word = word ;
0 commit comments