Skip to content

Commit 87a2701

Browse files
committed
word search solution
1 parent 5ba1877 commit 87a2701

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

word-search/Yn3-3xh.java

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
[문제풀이]
3+
- 이웃되는 알파벳이 이어져야 한다.
4+
- 각 알파벳은 한번만 호출되어야 한다.
5+
- DFS
6+
time: O(N M 4^L), space: O(L)
7+
8+
[회고]
9+
BFS로 풀면 되지 않을까 했지만, 최단경로를 찾는 것이 아니니 안 어울릴 것 같다.
10+
DFS로 풀자는 방법은 맞았지만, 풀이과정이 어려웠다.
11+
다시 풀어보면 좋을 것 같다.
12+
*/
13+
14+
class Solution {
15+
public boolean exist(char[][] board, String word) {
16+
int column = board.length;
17+
int row = board[0].length;
18+
boolean[][] visited = new boolean[column][row];
19+
20+
for (int i = 0; i < column; i++) {
21+
for (int j = 0; j < row; j++) {
22+
if (board[i][j] == word.charAt(0)) {
23+
if (dfs(board, word, visited, i, j, 0)) {
24+
return true;
25+
}
26+
}
27+
}
28+
}
29+
return false;
30+
}
31+
32+
private boolean dfs(char[][] board, String word, boolean[][] visited, int i, int j, int wordIndex) {
33+
if (wordIndex == word.length()) {
34+
return true;
35+
}
36+
37+
if (isVisited(board, word, visited, i, j, wordIndex)) {
38+
return false;
39+
}
40+
41+
visited[i][j] = true;
42+
if (dfs(board, word, visited, i + 1, j, wordIndex + 1) ||
43+
dfs(board, word, visited, i - 1, j, wordIndex + 1) ||
44+
dfs(board, word, visited, i, j + 1, wordIndex + 1) ||
45+
dfs(board, word, visited, i, j - 1, wordIndex + 1)
46+
) {
47+
return true;
48+
}
49+
50+
visited[i][j] = false;
51+
return false;
52+
}
53+
54+
private boolean isVisited(char[][] board, String word, boolean[][] visited, int i, int j, int wordIndex) {
55+
return i < 0 ||
56+
j < 0 ||
57+
i >= board.length ||
58+
j >= board[0].length ||
59+
visited[i][j] ||
60+
board[i][j] != word.charAt(wordIndex);
61+
}
62+
}
63+

0 commit comments

Comments
 (0)