Skip to content

Commit 300d1c1

Browse files
committed
Word Search
1 parent c955ca4 commit 300d1c1

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

word-search/forest000014.java

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/*
2+
Time Complexity: O(m * n * 4^(word.length))
3+
Space Complexity: O(m * n)
4+
*/
5+
6+
class Solution {
7+
boolean[][] visited;
8+
int m, n;
9+
int len;
10+
int[] dr = {-1, 0, 1, 0}; // clockwise traversal
11+
int[] dc = {0, 1, 0, -1};
12+
char board2[][];
13+
String word2;
14+
15+
public boolean exist(char[][] board, String word) {
16+
int[] cnt = new int[52];
17+
board2 = board;
18+
word2 = word;
19+
m = board.length;
20+
n = board[0].length;
21+
visited = new boolean[m][n];
22+
len = word.length();
23+
24+
// 1. for pruning, count characters in board and word respectively
25+
for (int i = 0; i < m; i++) {
26+
for (int j = 0; j < n; j++) {
27+
cnt[charToInt(board[i][j])]++;
28+
}
29+
}
30+
for (int i = 0; i < len; i++) {
31+
int idx = charToInt(word.charAt(i));
32+
if (--cnt[idx] < 0) {
33+
return false;
34+
}
35+
}
36+
37+
// 2. DFS
38+
for (int i = 0; i < m; i++) {
39+
for (int j = 0; j < n; j++) {
40+
if (board2[i][j] != word.charAt(0)) {
41+
continue;
42+
}
43+
if (dfs(i, j, 1)) {
44+
return true;
45+
}
46+
}
47+
}
48+
return false;
49+
}
50+
51+
private boolean dfs(int row, int col, int idx) {
52+
if (idx == len) { // end of word
53+
return true;
54+
}
55+
visited[row][col] = true;
56+
57+
for (int i = 0; i < 4; i++) {
58+
int nr = row + dr[i];
59+
int nc = col + dc[i];
60+
if (nr < 0 || nr >= m || nc < 0 || nc >= n) { // check boundary of the board
61+
continue;
62+
}
63+
if (visited[nr][nc]) { // check visited
64+
continue;
65+
}
66+
if (board2[nr][nc] == word2.charAt(idx)) {
67+
if (dfs(nr, nc, idx + 1)) {
68+
return true;
69+
}
70+
}
71+
}
72+
73+
visited[row][col] = false;
74+
return false;
75+
}
76+
77+
private int charToInt(char ch) {
78+
if (ch <= 'Z') {
79+
return ch - 'A';
80+
} else {
81+
return ch - 'a' + 26;
82+
}
83+
}
84+
}

0 commit comments

Comments
 (0)