-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordSearch.java
More file actions
32 lines (26 loc) · 1.06 KB
/
WordSearch.java
File metadata and controls
32 lines (26 loc) · 1.06 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
package ArraysD2;
public class WordSearch {
static private boolean[][] visited;
public static boolean exist(char[][] board, String word) {
int m = board.length;
int n = board[0].length;
visited = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == word.charAt(0) && dfs(board, i, j, 0, word)) return true;
}
}
return false;
}
public static boolean dfs(char[][] board, int i, int j, int index, String word) {
if (index == word.length()) return true;
if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] != word.charAt(index) || visited[i][j]) {
return false;
}
visited[i][j] = true;
// Great Technique.
boolean found = dfs(board, i + 1, j, index + 1, word) || dfs(board, i - 1, j, index + 1, word) || dfs(board, i, j + 1, index + 1, word) || dfs(board, i, j - 1, index + 1, word);
visited[i][j] = false;
return found;
}
}