-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathProblem_24.java
More file actions
60 lines (48 loc) · 1.92 KB
/
Problem_24.java
File metadata and controls
60 lines (48 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package strings;
//* Search a Word in a 2D Grid of characters.
public class Problem_24 {
public static boolean exist(char[][] board, String word) {
int rows = board.length;
int cols = board[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (board[i][j] == word.charAt(0) && dfs(board, i, j, word, 0)) {
return true; // Word found starting from this cell
}
}
}
return false; // Word not found in the grid
}
private static boolean dfs(char[][] board, int row, int col, String word, int index) {
if (index == word.length()) {
return true; // Entire word found
}
if (row < 0 || row >= board.length || col < 0 || col >= board[0].length
|| board[row][col] != word.charAt(index)) {
return false; // Out of bounds or character mismatch
}
// Mark the current cell as visited to avoid revisiting
char temp = board[row][col];
board[row][col] = '#';
boolean found = dfs(board, row - 1, col, word, index + 1) // Up
|| dfs(board, row + 1, col, word, index + 1) // Down
|| dfs(board, row, col - 1, word, index + 1) // Left
|| dfs(board, row, col + 1, word, index + 1); // Right
// Backtrack: reset the cell value after exploration
board[row][col] = temp;
return found;
}
public static void main(String[] args) {
char[][] board = {
{ 'A', 'B', 'C', 'E' },
{ 'S', 'F', 'C', 'S' },
{ 'A', 'D', 'E', 'E' }
};
String word = "ABCCED";
if (exist(board, word)) {
System.out.println("Word '" + word + "' found in the grid.");
} else {
System.out.println("Word '" + word + "' not found in the grid.");
}
}
}