본문 바로가기
프로그래머스/코딩테스트 고득점 kit

프로그래머스 깊이/너비 우선 탐색(DFS/BFS) LV3 - 단어변환

by 맴썰 2025. 9. 29.

https://school.programmers.co.kr/learn/courses/30/lessons/43163

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

BFS로 큐에서 뽑은 문자열과 단어 리스트 내의 문자열을 비교해 차이나는 문자의 개수가 1개인 문자열을 큐에 넣고 target이 나올 때까지 돌린 후 depth를 출력했다.

 

IDE를 안쓰니까 어색하다.

import java.util.*;
import java.util.stream.*;
class Solution {
    public int solution(String begin, String target, String[] words) {
        List<String> word = Arrays.stream(words).collect(Collectors.toList());
        if(!word.contains(target)) return 0;
        Queue<BFS> q = new LinkedList<>();
        boolean[] visited = new boolean[word.size()];
        q.offer(new BFS(begin,0));
        while(!q.isEmpty()){
            BFS temp = q.poll();
            String a = temp.t;
            int depth = temp.depth;
            if(word.indexOf(a)!=-1){
                if(visited[word.indexOf(a)]) continue;
                visited[word.indexOf(a)] = true;
            }
            if(target.equals(a)){
                return depth;
            }
            for(String b : word){
                if(getDiff(a,b)==1){
                    q.offer(new BFS(b,depth+1));
                }
            }
        }
        return 0;
    }
    
    public int getDiff(String a, String b){
        int count = 0;
        for(int i = 0; i<a.length(); i++){
            if(a.charAt(i)!=b.charAt(i)) count++;
        }
        return count;
    }
}

class BFS{
    String t;
    int depth;
    BFS(String t, int depth){
        this.t = t;
        this.depth = depth;
    }
}