kniost

谁怕,一蓑烟雨任平生

0%

LeetCode 79. Word Search

Difficulty: Medium

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

1
2
3
4
5
6
7
8
9
10
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

Solution

Language: 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
class Solution {
public boolean exist(char[][] board, String word) {
if (board == null || word == null) {
return false;
}
if (board.length == 0 || board[0].length == 0) {
return word.length() == 0;
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (search(board, i, j, word, 0)) {
return true;
}
}
}
return false;
}

int[] dx = {0, 1, 0, -1};
int[] dy = {1, 0, -1, 0};

private boolean search(char[][] board, int i, int j, String word, int cur) {
if (board[i][j] != word.charAt(cur)) {
return false;
}
if (cur == word.length() - 1) {
return true;
}
char tmp = board[i][j];
board[i][j] = '.';
for (int k = 0; k < 4; k++) {
int newX = i + dx[k];
int newY = j + dy[k];
if (newX >= 0 && newX < board.length &&
newY >= 0 && newY < board[0].length) {
if (search(board, newX, newY, word, cur + 1)) {
return true;
}
}
}
board[i][j] = tmp;
return false;


}
}