Repository navigation
Expand file tree
/
Copy pathHW_43163_2.java
More file actions
45 lines (41 loc) ยท 1.56 KB
/
Copy pathHW_43163_2.java
File metadata and controls
45 lines (41 loc) ยท 1.56 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
// ๊ท์น์๋ฐ๋ผ begin์์ target์ผ๋ก ๋ณํํ๋ ๊ฐ์ฅ ์งง์ ๋ณํ ๊ณผ์ ์ถ๋ ฅ
// ์๊ฐ ๋ณต์ก๋ : 3 <= ๋จ์ด์ ๊ธธ์ด <=10, 3<= words.length <=50 (์ค๋ณต ๋จ์ดX) O(V+E)
// ์ต์ ๋ณํ ํ์ ์ฐพ๊ธฐ : BFS
// ๋จ์ด ๋ณํ : ๊ฐ์ ์ผ๋ก ์๊ฐํ๊ณ , ํ๊ธ์ ์ฐจ์ด๋๋ ๋จ์ด๋ค์ ๊ฐ์ ์ผ๋ก ์ฐ๊ฒฐ ํ ๊ฐ์ ์ ์ถ๋ ฅ
import java.util.*;
class HW_43163_2 {
public int solution(String begin, String target, String[] words) {
Queue<String> queue = new LinkedList<>();
boolean[] visited = new boolean[words.length];
queue.add(begin);
int depth = 0;
while(!queue.isEmpty()){
for(int i=0; i<queue.size(); i++){
String cur = queue.poll();
if(cur.equals(target)){
return depth;
}
for(int j=0; j<words.length; j++){ // ๋ณํ ๊ฐ๋ฅํ ๋จ์ด ์ฐพ๊ธฐ
if(!visited[j] && check(cur, words[j])){
visited[j] = true;
queue.add(words[j]);
}
}
}
depth++;
}
return 0; // ๋ณํX -> 0
}
private static boolean check(String cur, String word){ // ํ๊ธ์๋ง ๋ค๋ฅธ์ง ์ฒดํฌํ๋ ํจ์
int cnt = 0; // ๋ค๋ฅธ ๊ธ์ ์
for(int i=0; i<cur.length(); i++){
if(cur.charAt(i) != word.charAt(i)){
cnt++; // ๋ค๋ฅธ ๊ธ์ ๊ฐ์ cnt
}
if(cnt > 1){
return false;
}
}
return true;
}
}