Skip to content

Commit 73ffb43

Browse files
authored
Create week 5 79. Word Search
1 parent ae5705b commit 73ffb43

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

week 5 79. Word Search

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
public class Solution {
2+
public boolean exist(char[][] board, String word) {
3+
if(word == null || word.length() == 0){
4+
return true;
5+
}
6+
char[] str = word.toCharArray();
7+
8+
for (int i = 0; i < board.length; i++){
9+
for(int j = 0; j < board[0].length; j++){
10+
if (helper(board, str, i, j, 0)){
11+
return true;
12+
}
13+
}
14+
}
15+
return false;
16+
}
17+
public boolean helper (char [][] board, char[] str, int i, int j, int pos){
18+
if(pos == str.length){
19+
return true;
20+
}
21+
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != str[pos]){
22+
return false;
23+
}
24+
char cur = board [i] [j];
25+
board [i] [j] = '$';
26+
boolean res = helper (board, str, i - 1, j, pos + 1)
27+
||helper (board, str, i + 1, j, pos + 1)
28+
||helper (board, str, i, j - 1, pos + 1)
29+
||helper (board, str, i, j + 1, pos + 1);
30+
board [i] [j] = cur;
31+
return res;
32+
}
33+
}

0 commit comments

Comments
 (0)