1+ import java .util .*;
12class Solution {
3+ public boolean [] visited ;
4+
5+ static class State {
6+ private final String word ;
7+ private final int cnt ;
8+
9+ public State (String word ,int cnt ){
10+ this .word = word ;
11+ this .cnt = cnt ;
12+ }
13+ }
14+
215 public int solution (String begin , String target , String [] words ) {
3- int answer = 0 ;
16+ visited = new boolean [words .length ];
17+ int answer = bfs (words ,begin ,target );
418 return answer ;
519 }
20+
21+ int bfs (String [] words ,String begin ,String target ) {
22+ Queue <State > queue = new LinkedList <>();
23+
24+ queue .offer (new State (begin ,0 ));
25+
26+ while (!queue .isEmpty ()){
27+ State current = queue .poll ();
28+ String currentWord = current .word ;
29+ int currentCnt = current .cnt ;
30+
31+ if (currentWord .equals (target )) {
32+ return currentCnt ;
33+ }
34+
35+ // 변환 가능한 단어 탐색
36+ for (int i = 0 ; i < words .length ; i ++){
37+ // 변환 가능하다면(단어 하나만 변경)
38+ if (!visited [i ] && canChange (currentWord ,words [i ])){
39+ visited [i ] = true ; // 방문 처리
40+ queue .offer (new State (words [i ],currentCnt + 1 ));
41+ }
42+ }
43+ }
44+ return 0 ;
45+ }
46+
47+ boolean canChange (String current , String target ){
48+ int diff = 0 ;
49+ char [] ch1 = current .toCharArray ();
50+ char [] ch2 = target .toCharArray ();
51+ for (int i = 0 ; i < current .length ();i ++){
52+ if (ch1 [i ] != ch2 [i ]) diff ++;
53+ if (diff > 1 ) {
54+ return false ;
55+ }
56+ }
57+ return true ;
58+ }
659}
0 commit comments