Skip to content

Commit 62add02

Browse files
committed
word-search solution
1 parent 47f3660 commit 62add02

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

word-search/hyeri0903.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
public boolean exist(char[][] board, String word) {
3+
/**
4+
- backtracking (DFS)
5+
- board[i][j] == word[0] 부터 start
6+
- 상하좌우 탐색, 같은 칸 중복 탐색 x
7+
- 틀리면 backtracking
8+
9+
*/
10+
11+
for(int i = 0; i< board.length; i++) {
12+
for(int j = 0; j< board[i].length; j++) {
13+
if(dfs(i, j, 0, board, word)) {
14+
return true;
15+
}
16+
}
17+
}
18+
return false;
19+
}
20+
21+
boolean dfs(int i, int j, int index, char[][] board, String word) {
22+
//모두 다 찾은 경우
23+
if(index == word.length()) return true;
24+
25+
//out of bound check
26+
if(i < 0 || j < 0 || i >= board.length || j>= board[i].length || board[i][j] != word.charAt(index)) return false;
27+
28+
//방문처리
29+
char cur = board[i][j];
30+
board[i][j] = '#';
31+
32+
//4방향 탐색
33+
boolean found = dfs(i+1, j, index+1, board, word) || dfs(i-1, j, index+1, board, word) || dfs(i, j+1, index+1, board, word) || dfs(i, j-1, index+1, board, word);
34+
35+
//backtracking
36+
board[i][j] = cur;
37+
38+
return found;
39+
}
40+
}

0 commit comments

Comments
 (0)