forked from silent-killer-11/Hacktoberfest-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWord_Search.java
More file actions
50 lines (38 loc) · 1.09 KB
/
Copy pathWord_Search.java
File metadata and controls
50 lines (38 loc) · 1.09 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
package Lec29;
public class Word_Search {
public static void main(String[] args) {
char[][] maze = { { 'A', 'B', 'C', 'E' }, { 'S', 'F', 'C', 'S' }, { 'A', 'D', 'E', 'E' } };
String word = "ABCCED";
for (int i = 0; i < maze.length; i++) {
for (int j = 0; j < maze[0].length; j++) {
if (maze[i][j] == word.charAt(0)) {
boolean ans = findword(maze, i, j, word, 0);//
if (ans == true) {
System.out.println(ans);
return;
}
}
}
}
System.out.println(false);
}
public static boolean findword(char[][] maze, int cr, int cc, String word, int idx) {
if (idx == word.length()) {
return true;
}
if (cc < 0 || cc >= maze[0].length || cr < 0 || cr >= maze.length || maze[cr][cc] != word.charAt(idx)) {
return false;
}
int[] r = { -1, 1, 0, 0, -1, 1, 1, -1 };
int[] c = { 0, 0, 1, -1, 1, 1, -1, -1 };
maze[cr][cc] = '*';
for (int i = 0; i < c.length; i++) {
boolean ans = findword(maze, cr + r[i], cc + c[i], word, idx + 1);
if (ans == true) {
return ans;
}
}
maze[cr][cc] = word.charAt(idx);// undo
return false;
}
}