본문 바로가기

알고리즘

[PGS] 프로그래머스 - 단어 변환 (JAVA)

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

import java.util.*;
import java.io.*;

class Info{
    String word;
    int depth;
    
    Info(String word, int depth){
        this.word = word;
        this.depth = depth;
    }
}

class Solution {
    
    static boolean[] visited;
    static Queue<Info> queue;
    
    static int answer;

    static void start(String target, String[] words){

        while(!queue.isEmpty()){
            Info tmp = queue.poll();

            if(tmp.word.equals(target)){
                if(answer>tmp.depth) {
                    answer=tmp.depth;
                }
            }

            for(int i=0;i<words.length;i++){
                int dif=0;
                for(int j=0;j<tmp.word.length();j++){
                    if(tmp.word.charAt(j)!=words[i].charAt(j)){
                        dif++;
                    }
                }
                if(dif==1&&!visited[i]){
                    queue.add(new Info(words[i],tmp.depth+1));
                    visited[i]=true;
                }
            }  
        }
        
    }
    public int solution(String begin, String target, String[] words) {
        answer = Integer.MAX_VALUE;
        int max = Integer.MAX_VALUE;
        queue = new LinkedList<>();
        visited = new boolean[words.length];
        queue.add(new Info(begin,0));
        start(target, words);
        if(answer==max) answer = 0;
        return answer;
    }
}

스스로가 벽이라고 느끼던 bfs 문제를 혼자 힘으로 풀어서 너무 뿌듯하다 !