Skip to content

Commit a03c011

Browse files
committed
add solution of word-search
1 parent 6cd9569 commit a03c011

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

word-search/jinhyungrhee.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+
boolean[][] visited = new boolean[board.length][board[0].length];
5+
6+
for (int i = 0; i < board.length; i++) {
7+
for (int j = 0; j < board[0].length; j++) {
8+
if(dfs(board, word, visited, i, j, 0)) {
9+
return true;
10+
}
11+
}
12+
}
13+
return false;
14+
}
15+
16+
public boolean dfs(char[][] board, String word, boolean[][] visited, int x, int y, int index) {
17+
18+
// [성공] : 모든 글자 매칭 성공
19+
if (index == word.length()) return true;
20+
21+
// [실패] : 범위 초과, 방문함, 글자 불일치
22+
if (x < 0 || x >= board.length || y < 0 || y >= board[0].length ||
23+
visited[x][y] || board[x][y] != word.charAt(index)) {
24+
return false;
25+
}
26+
27+
visited[x][y] = true;
28+
int[][] dir = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};
29+
for (int i = 0; i < 4; i++) {
30+
int newX = x + dir[i][0], newY = y + dir[i][1];
31+
if (dfs(board, word, visited, newX, newY, index + 1)) {
32+
return true; // 찾았으면 바로 리턴
33+
}
34+
}
35+
visited[x][y] = false; // backtrack
36+
37+
return false; // 4방향 다 실패하면 false
38+
39+
}
40+
}

0 commit comments

Comments
 (0)