-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDH_43163_2.java
More file actions
53 lines (38 loc) · 1.36 KB
/
DH_43163_2.java
File metadata and controls
53 lines (38 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.util.*;
/*
단어 변환
*/
class DH_43163_2 {
public int solution(String begin, String target, String[] words) {
int answer = 0;
// bfs로 구현하기 위해 ArrayDeque와 방문 배열 선언
// ArrayDeuqe [0]: words에서의 idx, [1]: 깊이
ArrayDeque<int[]> q = new ArrayDeque<>();
boolean v[] = new boolean[words.length];
// begin의 idx는 -1로 설정
q.add(new int[] {-1, 0});
while(!q.isEmpty()) {
int[] current = q.poll();
String str = current[0] == -1 ? begin: words[current[0]];
if(str.equals(target)) {
answer = current[1];
break;
}
for(int i = 0; i < words.length; i++) {
if(v[i] || !check(words[i], str)) continue;
v[i] = true;
q.add(new int[] {i, current[1] + 1});
}
}
return answer;
}
// 입력된 두 문자열이 문자 하나만 다를 때
static boolean check(String s1, String s2) {
int diffCnt = 0;
for(int i = 0; i < s1.length(); i++) {
if(s1.charAt(i) != s2.charAt(i)) diffCnt += 1;
if(diffCnt > 1) return false;
}
return true;
}
}