-
Notifications
You must be signed in to change notification settings - Fork 200
Expand file tree
/
Copy pathwordSearch.java
More file actions
29 lines (26 loc) · 1.07 KB
/
wordSearch.java
File metadata and controls
29 lines (26 loc) · 1.07 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
// Please check link for explanation of code below
// https://leetcode.com/problems/word-search/discuss/27658/Accepted-very-short-Java-solution.-No-additional-space.
// Additional solutions
// Straightforward - https://leetcode.com/problems/word-search/discuss/27811/My-Java-solution
// DFS approach - https://leetcode.com/problems/word-search/discuss/27765/Java-DFS-solution-beats-97.64
public boolean exist(char[][] board, String word) {
char[] w = word.toCharArray();
for (int y=0; y<board.length; y++) {
for (int x=0; x<board[y].length; x++) {
if (exist(board, y, x, w, 0)) return true;
}
}
return false;
}
private boolean exist(char[][] board, int y, int x, char[] word, int i) {
if (i == word.length) return true;
if (y<0 || x<0 || y == board.length || x == board[y].length) return false;
if (board[y][x] != word[i]) return false;
board[y][x] ^= 256;
boolean exist = exist(board, y, x+1, word, i+1)
|| exist(board, y, x-1, word, i+1)
|| exist(board, y+1, x, word, i+1)
|| exist(board, y-1, x, word, i+1);
board[y][x] ^= 256;
return exist;
}