Skip to content

Commit 563ba95

Browse files
authored
Update Word Search.java
1 parent 03349e8 commit 563ba95

File tree

1 file changed

+28
-29
lines changed

1 file changed

+28
-29
lines changed

Medium/Word Search.java

Lines changed: 28 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,33 @@
11
class Solution {
2-
3-
private final int[][] DIRS = {{1, 0}, {0, 1}, {0, -1}, {-1, 0}};
4-
5-
public boolean exist(char[][] board, String word) {
6-
int m = board.length;
7-
int n = board[0].length;
8-
for (int i = 0; i < board.length; i++) {
9-
for (int j = 0; j < board[0].length; j++) {
10-
if (found(board, i, j, word, 0, m, n)) {
11-
return true;
2+
3+
private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
4+
5+
public boolean exist(char[][] board, String word) {
6+
int m = board.length;
7+
int n = board[0].length;
8+
for (int i = 0; i < m; i++) {
9+
for (int j = 0; j < n; j++) {
10+
if (isFound(board, word, 0, i, j, m, n)) {
11+
return true;
12+
}
13+
}
1214
}
13-
}
15+
return false;
1416
}
15-
return false;
16-
}
17-
18-
private boolean found(char[][] board, int x, int y, String word, int idx, int m, int n) {
19-
if (idx == word.length()) {
20-
return true;
21-
}
22-
if (x < 0 || x == m || y < 0 || y == n || board[x][y] != word.charAt(idx)) {
23-
return false;
24-
}
25-
board[x][y] = '#';
26-
for (int[] dir : DIRS) {
27-
if (found(board, x + dir[0], y + dir[1], word, idx + 1, m, n)) {
28-
return true;
29-
}
17+
18+
private boolean isFound(char[][] board, String word, int idx, int row, int col, int m, int n) {
19+
if (idx == word.length()) {
20+
return true;
21+
}
22+
if (row < 0 || col < 0 || row >= m || col >= n || board[row][col] != word.charAt(idx)) {
23+
return false;
24+
}
25+
board[row][col] ^= 256;
26+
boolean result = false;
27+
for (int[] dir : DIRS) {
28+
result = result || isFound(board, word, idx + 1, row + dir[0], col + dir[1], m, n);
29+
}
30+
board[row][col] ^= 256;
31+
return result;
3032
}
31-
board[x][y] = word.charAt(idx);
32-
return false;
33-
}
3433
}

0 commit comments

Comments
 (0)