Skip to content

Commit cb6ec25

Browse files
authored
Merge pull request #1408 from AlgorithmWithGod/lkhyun
[20251114] PGM / Lv3 / 단어 변환 / 이강현
2 parents 6ad258b + 115cac1 commit cb6ec25

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
```java
2+
class Solution {
3+
static int answer;
4+
static boolean[] visited;
5+
6+
public int solution(String begin, String target, String[] words) {
7+
boolean hasTarget = false;
8+
for(String word : words) {
9+
if(word.equals(target)) {
10+
hasTarget = true;
11+
break;
12+
}
13+
}
14+
if(!hasTarget) return 0;
15+
16+
answer = Integer.MAX_VALUE;
17+
visited = new boolean[words.length];
18+
DFS(begin, target, words, 0);
19+
20+
return answer == Integer.MAX_VALUE ? 0 : answer;
21+
}
22+
23+
public static void DFS(String from, String target, String[] words, int depth){
24+
if(target.equals(from)){
25+
answer = Math.min(answer, depth);
26+
return;
27+
}
28+
29+
for(int i = 0; i < words.length; i++){
30+
if(visited[i]) continue;
31+
32+
if(isOneDifferent(from, words[i])){
33+
visited[i] = true;
34+
DFS(words[i], target, words, depth + 1);
35+
visited[i] = false;
36+
}
37+
}
38+
}
39+
40+
private static boolean isOneDifferent(String word1, String word2) {
41+
int diff = 0;
42+
for(int i = 0; i < word1.length(); i++){
43+
if(word1.charAt(i) != word2.charAt(i)){
44+
diff++;
45+
if(diff > 1) return false;
46+
}
47+
}
48+
return diff == 1;
49+
}
50+
}
51+
```

0 commit comments

Comments
 (0)