Skip to content

Commit f7408cb

Browse files
committed
Word Search solution
1 parent ada0cc4 commit f7408cb

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

word-search/kimjunyoung90.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
public boolean exist(char[][] board, String word) {
3+
4+
int rows = board.length;
5+
int columns = board[0].length;
6+
boolean[][] visited = new boolean[rows][columns];
7+
for (int i = 0; i < rows; i++) {
8+
for (int j = 0; j < columns; j++) {
9+
if (dfs(board, word, i, j, 0, visited)) {
10+
return true;
11+
}
12+
}
13+
}
14+
return false;
15+
}
16+
17+
private boolean dfs(char[][] board, String word, int row, int col, int idx, boolean[][] visited) {
18+
//예외 처리 1
19+
if (idx == word.length()) return true;
20+
21+
//예외 처리 2
22+
if (row < 0 || col < 0 || row >= board.length || col >= board[0].length) return false;
23+
24+
//예외 처리 3
25+
if (visited[row][col]) return false;
26+
27+
//1. 글자 체크
28+
if (board[row][col] != word.charAt(idx)) return false;
29+
30+
//방문 처리
31+
visited[row][col] = true;
32+
33+
//상, 하, 좌, 우 찾기
34+
boolean found = dfs(board, word, row + 1, col, idx + 1, visited)
35+
|| dfs(board, word, row - 1, col, idx + 1, visited)
36+
|| dfs(board, word, row, col + 1, idx + 1, visited)
37+
|| dfs(board, word, row, col - 1, idx + 1, visited);
38+
39+
visited[row][col] = false;
40+
return found;
41+
}
42+
}

0 commit comments

Comments
 (0)