Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 1b81435

Browse files
authored
Update Word Search.java
1 parent 9728a5b commit 1b81435

File tree

1 file changed

+14
-14
lines changed

1 file changed

+14
-14
lines changed

Medium/Word Search.java

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
11
class Solution {
2-
public int[][] dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
2+
public static final int[][] DIRS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
3+
34
public boolean exist(char[][] board, String word) {
4-
if (board.length == 0 || board[0].length == 0) {
5-
return false;
6-
}
5+
int rows = board.length;
6+
int cols = board[0].length;
77
for (int i = 0; i < board.length; i++) {
88
for (int j = 0; j < board[0].length; j++) {
9-
if (exists(board, i, j, word, 0, new boolean[board.length][board[0].length])) {
9+
if (dfs(board, word, 0, new boolean[rows][cols], i, j)) {
1010
return true;
1111
}
1212
}
1313
}
1414
return false;
15-
}
16-
17-
private boolean exists(char[][] board, int i, int j, String word, int idx, boolean[][] visited) {
15+
}
16+
17+
private boolean dfs(char[][] board, String word, int idx, boolean[][] visited, int i, int j) {
1818
if (idx == word.length()) {
1919
return true;
2020
}
21-
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || visited[i][j] || word.charAt(idx) != board[i][j]) {
21+
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || visited[i][j]
22+
|| board[i][j] != word.charAt(idx)) {
2223
return false;
2324
}
2425
visited[i][j] = true;
25-
for (int[] dir : dirs) {
26-
if (exists(board, i + dir[0], j + dir[1], word, idx + 1, visited)) {
27-
return true;
28-
}
26+
boolean ans = false;
27+
for (int[] dir : DIRS) {
28+
ans = ans || dfs(board, word, idx + 1, visited, i + dir[0], j + dir[1]);
2929
}
3030
visited[i][j] = false;
31-
return false;
31+
return ans;
3232
}
3333
}

0 commit comments

Comments
 (0)