Skip to content

Commit 58eee0d

Browse files
committed
feat: 79. Word Search solution
1 parent 03671de commit 58eee0d

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

word-search/Yiseull.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
3+
private final int[] dx = {-1, 1, 0, 0};
4+
private final int[] dy = {0, 0, -1, 1};
5+
6+
public boolean exist(char[][] board, String word) {
7+
for (int i = 0; i < board.length; i++) {
8+
for (int j = 0; j < board[0].length; j++) {
9+
if (board[i][j] == word.charAt(0) && dfs(board, word, i, j, 1)) {
10+
return true;
11+
}
12+
}
13+
}
14+
15+
return false;
16+
}
17+
18+
private boolean dfs(char[][] board, String word, int x, int y, int index) {
19+
if (index == word.length()) return true;
20+
21+
char tmp = board[x][y];
22+
board[x][y] = '0';
23+
24+
for (int i = 0; i < 4; i++) {
25+
int nextX = x + dx[i], nextY = y + dy[i];
26+
if (0 <= nextX && nextX < board.length && 0 <= nextY && nextY < board[0].length && board[nextX][nextY] == word.charAt(index)) {
27+
if(dfs(board, word, nextX, nextY, index + 1)) return true;
28+
}
29+
}
30+
31+
board[x][y] = tmp;
32+
33+
return false;
34+
}
35+
}

0 commit comments

Comments
 (0)