LeetCode - Word Search
Problem description
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.
Analysis
A typical backtrack problem.
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
51
52
class Solution {
public boolean exist(char[][] board, String word) {
char s = word.charAt(0);
boolean[][] visited = new boolean[board.length][board[0].length];
for (int i = 0; i < board.length; i++){
for (int j = 0; j < board[0].length; j++){
if (board[i][j] == s){
if (dfs(board, word, i, j, visited, 0)){
return true;
}
}
}
}
return false;
}
int[][] dir = new int[][]{ {1,0}, {-1,0}, {0,1}, {0,-1} };
boolean dfs(char[][] board, String word, int i, int j, boolean[][] visited, int start){
int row = board.length;
int col = board[0].length;
if (start == word.length()){
return true;
}
if (i < 0 || i >= row || j < 0 || j >= col || visited[i][j] || board[i][j] != word.charAt(start)){
return false;
}
visited[i][j] = true;
for (int[] d:dir){
int ni = i + d[0];
int nj = j + d[1];
if (dfs(board, word, ni, nj, visited, start+1)){
return true;
}
}
visited[i][j] = false;
return false;
}
}
What to improve
- think carefully