Skip to content

Commit 790350b

Browse files
committed
Word Search
1 parent ddc9916 commit 790350b

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

word-search/TonyKim9401.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// TC: O(n * m * 4^k);
2+
// -> The size of board: n * m
3+
// -> Check 4 directions by the given word's length: 4^k
4+
// SC: O(n * m + k)
5+
// -> boolean 2D array: n * M
6+
// -> recursive max k spaces
7+
class Solution {
8+
public boolean exist(char[][] board, String word) {
9+
// Mark visited path to do not go back.
10+
boolean[][] visit;
11+
12+
for (int i = 0; i < board.length; i++) {
13+
for (int j = 0; j < board[0].length; j++) {
14+
visit = new boolean[board.length][board[0].length];
15+
if (wordSearch(i, j, 0, word, board, visit)) return true;
16+
}
17+
}
18+
return false;
19+
}
20+
21+
private boolean wordSearch(int i, int j, int idx, String word, char[][] board, boolean[][] visit) {
22+
23+
// When idx checking reach to the end of the length of the word then, return true
24+
if (idx == word.length()) return true;
25+
26+
// Check if i and j are inside of the range
27+
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) return false;
28+
29+
// Check if the coordinate equals to the charactor value
30+
if (board[i][j] != word.charAt(idx)) return false;
31+
if (visit[i][j]) return false;
32+
33+
// Mark the coordinate as visited
34+
visit[i][j] = true;
35+
36+
// If visited, the target is gonna be the next charactor
37+
idx += 1;
38+
39+
// If any direction returns true then it is true
40+
if (
41+
wordSearch(i+1, j, idx, word, board, visit) ||
42+
wordSearch(i-1, j, idx, word, board, visit) ||
43+
wordSearch(i, j+1, idx, word, board, visit) ||
44+
wordSearch(i, j-1, idx, word, board, visit)
45+
) return true;
46+
47+
// If visited wrong direction, turns it as false
48+
visit[i][j] = false;
49+
50+
return false;
51+
}
52+
}

0 commit comments

Comments
 (0)