-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0079-word-search.java
49 lines (46 loc) · 1.48 KB
/
0079-word-search.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//This is a typical backtracking problem similar to Number of Islands.
//In number of Isalnds, we sinked the islands. Here, we will do the same by adding changing the value of the char.
//I added 100 because it will exceed the ascii limit for characters and will change it to some ascii value which is not an alphabet.
class Solution {
public boolean exist(char[][] board, String word) {
int m = board.length;
int n = board[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (check(board, word, i, j, m, n, 0)) {
return true;
}
}
}
return false;
}
public boolean check(
char[][] board,
String word,
int i,
int j,
int m,
int n,
int cur
) {
if (cur >= word.length()) return true;
if (
i < 0 ||
j < 0 ||
i >= m ||
j >= n ||
board[i][j] != word.charAt(cur)
) return false;
boolean exist = false;
if (board[i][j] == word.charAt(cur)) {
board[i][j] += 100;
exist =
check(board, word, i + 1, j, m, n, cur + 1) ||
check(board, word, i, j + 1, m, n, cur + 1) ||
check(board, word, i - 1, j, m, n, cur + 1) ||
check(board, word, i, j - 1, m, n, cur + 1);
board[i][j] -= 100;
}
return exist;
}
}