Skip to content

Commit 0e4d8c4

Browse files
committed
solve word search
1 parent 23d8c7a commit 0e4d8c4

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

word-search/sora0319.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
public boolean exist(char[][] board, String word) {
3+
boolean[][] visited = new boolean[board.length][board[0].length];
4+
boolean status = false;
5+
6+
for(int i = 0; i < board.length; i++){
7+
for(int j = 0; j < board[0].length; j++){
8+
if(word.charAt(0) == board[i][j]){
9+
visited[i][j] = true;
10+
status = checkingWord(board, word, visited, 1, i, j);
11+
visited[i][j] = false;
12+
}
13+
if(status) return true;
14+
}
15+
}
16+
17+
return false;
18+
}
19+
public boolean checkingWord(char[][] board, String word, boolean[][] visited, int same, int x, int y){
20+
if(same == word.length()) return true;
21+
int[] mx = {-1,1,0,0};
22+
int[] my = {0,0,-1,1};
23+
24+
for(int k = 0; k < 4; k++){
25+
int nx = mx[k] + x;
26+
int ny = my[k] + y;
27+
28+
if(nx < 0 || ny < 0 || nx >= board.length || ny >= board[0].length) continue;
29+
if(visited[nx][ny]) continue;
30+
31+
boolean status = false;
32+
33+
if(word.charAt(same) == board[nx][ny]){
34+
visited[nx][ny] = true;
35+
if(checkingWord(board, word, visited, same + 1, nx, ny)) return true;
36+
visited[nx][ny] = false;
37+
}
38+
}
39+
return false;
40+
}
41+
}
42+

0 commit comments

Comments
 (0)