Skip to content

Commit a3b309d

Browse files
committed
word search
1 parent 5e60d76 commit a3b309d

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package backtracking;
2+
3+
// https://leetcode.com/problems/word-search/
4+
public class WordSearch {
5+
6+
public static void main(String[] args) {
7+
WordSearch obj = new WordSearch();
8+
char[][] board = {{'A','B','C','E'},
9+
{'S','F','C','S'},
10+
{'A','D','E','E'}};
11+
//String word = "ABCCED";
12+
//String word = "SEE";
13+
String word = "ABCB";
14+
boolean result = obj.exist(board, word);
15+
System.out.println("result > " + result);
16+
}
17+
18+
public boolean exist(char[][] board, String word) {
19+
// check edge
20+
if (word == null || word.length() == 0) {
21+
return true;
22+
}
23+
if (board == null || board.length == 0 || board[0].length == 0) {
24+
return false;
25+
}
26+
// used boolean
27+
boolean[][] used = new boolean[board.length][board[0].length];
28+
29+
// dfs
30+
for (int row = 0; row < board.length; row++) {
31+
for (int col = 0; col < board[row].length; col++) {
32+
if (dfs(board, word, used, row, col, 0)) {
33+
return true;
34+
}
35+
}
36+
}
37+
38+
39+
return false;
40+
}
41+
42+
private boolean dfs(char[][] board, String word, boolean[][] used, int row, int col, int wordIndex) {
43+
if (word == null || wordIndex == word.length()) {
44+
return true;
45+
}
46+
char currentChar = word.charAt(wordIndex);
47+
if (row < 0 || col < 0
48+
|| row >= board.length || col >= board[row].length
49+
|| currentChar != board[row][col] || used[row][col])
50+
{
51+
return false;
52+
}
53+
// mark use
54+
used[row][col] = true;
55+
boolean result = dfs(board, word, used, row + 1, col, wordIndex + 1)
56+
|| dfs(board, word, used, row - 1, col, wordIndex + 1)
57+
|| dfs(board, word, used, row, col + 1, wordIndex + 1)
58+
|| dfs(board, word, used, row, col - 1, wordIndex + 1);
59+
60+
// mark not use
61+
used[row][col] = false;
62+
63+
return result;
64+
}
65+
}

0 commit comments

Comments
 (0)