-
Notifications
You must be signed in to change notification settings - Fork 0
/
week 5 79. Word Search
33 lines (32 loc) · 1.08 KB
/
week 5 79. 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
public class Solution {
public boolean exist(char[][] board, String word) {
if(word == null || word.length() == 0){
return true;
}
char[] str = word.toCharArray();
for (int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if (helper(board, str, i, j, 0)){
return true;
}
}
}
return false;
}
public boolean helper (char [][] board, char[] str, int i, int j, int pos){
if(pos == str.length){
return true;
}
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != str[pos]){
return false;
}
char cur = board [i] [j];
board [i] [j] = '$';
boolean res = helper (board, str, i - 1, j, pos + 1)
||helper (board, str, i + 1, j, pos + 1)
||helper (board, str, i, j - 1, pos + 1)
||helper (board, str, i, j + 1, pos + 1);
board [i] [j] = cur;
return res;
}
}