-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDay-21 Word Search
36 lines (29 loc) · 1.06 KB
/
Day-21 Word Search
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
class Solution {
public boolean exist(char[][] board, String word) {
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
if(board[i][j]==word.charAt(0) && search(board, word, i, j, 0))
return true;
}
}
return false;
}
boolean search(char[][] board, String word, int i, int j, int wordIndex) {
if(i < 0 || j < 0
|| i == board.length || j == board[0].length
|| board[i][j] == '#' || board[i][j] != word.charAt(wordIndex)) {
return false;
}
if(wordIndex == word.length() - 1)
return true;
char c = board[i][j];
board[i][j] = '#';
if (search(board, word, i, j+1, wordIndex+1) ||
search(board, word, i, j-1, wordIndex+1) ||
search(board, word, i-1, j, wordIndex+1) ||
search(board, word, i+1, j, wordIndex+1))
return true;
board[i][j] = c;
return false;
}
}