Skip to content

Commit cdc4180

Browse files
committed
feat: word-search solution
1 parent be0becc commit cdc4180

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

word-search/sm9171.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+
if (board == null || board.length == 0 || word == null || word.length() == 0) {
4+
return false;
5+
}
6+
7+
int rows = board.length;
8+
int cols = board[0].length;
9+
boolean[][] visited = new boolean[rows][cols];
10+
11+
for (int i = 0; i < rows; i++) {
12+
for (int j = 0; j < cols; j++) {
13+
if (dfs(board, visited, i, j, word, 0)) {
14+
return true;
15+
}
16+
}
17+
}
18+
return false;
19+
}
20+
21+
private static boolean dfs(char[][] board, boolean[][] visited, int i, int j, String word, int index) {
22+
if (index == word.length()) {
23+
return true;
24+
}
25+
26+
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || visited[i][j] || board[i][j] != word.charAt(index)) {
27+
return false;
28+
}
29+
30+
31+
visited[i][j] = true;
32+
33+
boolean found = dfs(board, visited, i + 1, j, word, index + 1) ||
34+
dfs(board, visited, i - 1, j, word, index + 1) ||
35+
dfs(board, visited, i, j + 1, word, index + 1) ||
36+
dfs(board, visited, i, j - 1, word, index + 1);
37+
38+
visited[i][j] = false;
39+
40+
return found;
41+
}
42+
}

0 commit comments

Comments
 (0)