Skip to content

Commit ebcbde0

Browse files
committed
Add word search solution
1 parent 60f392b commit ebcbde0

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

word-search/jaekwang97.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Solution {
2+
3+
static int[] dx = {0, 1, 0, -1};
4+
static int[] dy = {1, 0, -1, 0};
5+
static int n, m;
6+
7+
public boolean exist(char[][] board, String word) {
8+
m = board[0].length;
9+
n = board.length;
10+
11+
for (int i = 0; i < n; i++) {
12+
for (int j = 0; j < m; j++) {
13+
if (board[i][j] != word.charAt(0)) continue;
14+
15+
char cur = board[i][j];
16+
board[i][j] = '#';
17+
boolean flag = dfs(board, word, 1, i, j);
18+
board[i][j] = cur;
19+
20+
if (flag) return true;
21+
}
22+
}
23+
24+
return false;
25+
}
26+
27+
private static boolean dfs(
28+
char[][] board,
29+
String word,
30+
int idx,
31+
int x,
32+
int y
33+
) {
34+
if (idx == word.length()) return true;
35+
36+
for (int i = 0; i < 4; i++) {
37+
int nx = x + dx[i];
38+
int ny = y + dy[i];
39+
40+
if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
41+
if (board[nx][ny] != word.charAt(idx)) continue;
42+
43+
char cur = board[nx][ny];
44+
board[nx][ny] = '#';
45+
46+
boolean flag = dfs(board, word, idx + 1, nx, ny);
47+
48+
board[nx][ny] = cur;
49+
50+
if (flag) return true;
51+
}
52+
53+
return false;
54+
}
55+
}

0 commit comments

Comments
 (0)