Skip to content

Commit af5c584

Browse files
committed
word search
1 parent d13f273 commit af5c584

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

word-search/se6816.java

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
2+
/**
3+
DFS를 통해 이중 배열에서 문자를 찾는 방식
4+
board의 길이 -> M
5+
board[i]의 길이 -> N
6+
시간 복잡도 : O(M*N)
7+
공간 복잡도 : O(M*N)
8+
*/
9+
class Solution {
10+
public static int[] moveX = {0, -1, 1, 0};
11+
public static int[] moveY = {-1, 0, 0, 1};
12+
public int N;
13+
public int M;
14+
public boolean exist(char[][] board, String word) {
15+
M = board.length;
16+
N = board[0].length;
17+
boolean result = false;
18+
char startCh = word.charAt(0);
19+
for(int i = 0; i < M; i++) {
20+
for(int j = 0; j < N; j++) {
21+
if(board[i][j] != startCh) {
22+
continue;
23+
}
24+
boolean[][] visited = new boolean[M][N];
25+
visited[i][j] = true;
26+
result = result || search(board, visited, i, j, 1, word);
27+
}
28+
}
29+
return result;
30+
}
31+
32+
public boolean search(char[][] board, boolean[][] visited, int x, int y, int len, String target) {
33+
if(len >= target.length()) {
34+
return true;
35+
}
36+
37+
boolean result = false;
38+
39+
for(int i = 0; i < 4; i++) {
40+
int tempX = x + moveX[i];
41+
int tempY = y + moveY[i];
42+
43+
if(outOfIndex(tempX, tempY)) {
44+
continue;
45+
}
46+
47+
if(visited[tempX][tempY]) {
48+
continue;
49+
}
50+
51+
if(board[tempX][tempY] != target.charAt(len)) {
52+
continue;
53+
}
54+
55+
visited[tempX][tempY] = true;
56+
result = search(board, visited, tempX, tempY, len + 1, target) || result;
57+
if(result) {
58+
break;
59+
}
60+
visited[tempX][tempY] = false;
61+
}
62+
63+
return result;
64+
}
65+
66+
public boolean outOfIndex(int x, int y){
67+
if(x < 0 || x >= M || y < 0 || y >= N) {
68+
return true;
69+
}
70+
71+
return false;
72+
}
73+
}

0 commit comments

Comments
 (0)