-
Notifications
You must be signed in to change notification settings - Fork 2
/
79.word-search.java
50 lines (43 loc) · 1.43 KB
/
79.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
50
/*
* @lc app=leetcode id=79 lang=java
*
* [79] Word Search
*/
// @lc code=start
class Solution {
public boolean exist(char[][] board, String word) {
if (word == null || word.length() == 0) {
return false;
}
int m = board.length;
int n = board[0].length;
boolean[][] visited = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (word.charAt(0) == board[i][j] && helper(board, visited, word, i, j, 0)) {
return true;
}
}
}
return false;
}
public boolean helper(char[][] board, boolean[][] visited, String word, int row, int col, int index) {
if (index == word.length()) {
return true;
}
if (row < 0 || row >= board.length || col < 0 || col >= board[0].length || board[row][col] != word.charAt(index)
|| visited[row][col]) {
return false;
}
visited[row][col] = true;
if (helper(board, visited, word, row + 1, col, index + 1)
|| helper(board, visited, word, row - 1, col, index + 1)
|| helper(board, visited, word, row, col + 1, index + 1)
|| helper(board, visited, word, row, col - 1, index + 1)) {
return true;
}
visited[row][col] = false;
return false;
}
}
// @lc code=end