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
34
|
class Solution {
public boolean exist(char[][] board, String word) {
// Ref: https://leetcode.com/problems/word-search/discuss/27834/Simple-solution
if (board == null || board.length == 0 && board[0].length < word.length()) return false;
char[] target = word.toCharArray();
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (search(board, i, j, 0, target)) return true;
}
}
return false;
}
private boolean search(char[][] board, int i, int j, int pos, char[] target) {
if (pos >= target.length ) return true;
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) return false;
if (board[i][j] == target[pos]) {
char c = board[i][j];
board[i][j] = '#';
boolean res = search(board, i + 1, j, pos + 1, target) ||
search(board, i , j + 1, pos + 1, target)||
search(board, i - 1, j, pos + 1, target) ||
search(board, i, j - 1, pos + 1, target);
board[i][j] = c;
return res;
}
return false;
}
}
|