-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWordSearch.java
33 lines (32 loc) · 1.1 KB
/
WordSearch.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// WordSearch.java
class Solution {
private boolean dfs(int r, int c, int i, int rows, int cols, char[][] board, String word){
if (i == word.length()) {
return true;
}
if (r < 0 || r >= rows || c < 0 || c >= cols || word.charAt(i) != board[r][c] ||
board[r][c] == '#') {
return false;
}
char ch = board[r][c];
board[r][c] = '#';
boolean result;
result = dfs(r + 1, c, i + 1, rows, cols, board, word) ||
dfs(r, c + 1, i + 1, rows, cols, board, word) ||
dfs(r - 1, c, i + 1, rows, cols, board, word) ||
dfs(r, c - 1, i + 1, rows, cols, board, word);
board[r][c] = ch;
return result;
}
public boolean exist(char[][] board, String word) {
int rows = board.length, cols = board[0].length;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (dfs(r,c, 0, rows, cols, board, word)) {
return true;
}
}
}
return false;
}
}