Algorithm Test/프로그래머스

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

김맷돌 2021. 4. 1. 15:17
반응형

🔎 단어 변환

 

BFS를 이용해 간단히 해결할 수 있었다.

 


문제 설명

 

두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다.

 

  1. 한 번에 한 개의 알파벳만 바꿀 수 있습니다.
  2. words에 있는 단어로만 변환할 수 있습니다.

예를 들어 begin이 "hit", target가 "cog", words가 ["hot","dot","dog","lot","log","cog"]라면 "hit" -> "hot" -> "dot" -> "dog" -> "cog"와 같이 4단계를 거쳐 변환할 수 있습니다.

 

두 개의 단어 begin, target과 단어의 집합 words가 매개변수로 주어질 때, 최소 몇 단계의 과정을 거쳐 begin을 target으로 변환할 수 있는지 return 하도록 solution 함수를 작성해주세요.

 

제한 사항

  • 각 단어는 알파벳 소문자로만 이루어져 있습니다.
  • 각 단어의 길이는 3 이상 10 이하이며 모든 단어의 길이는 같습니다.
  • words에는 3개 이상 50개 이하의 단어가 있으며 중복되는 단어는 없습니다.
  • begin과 target은 같지 않습니다.
  • 변환할 수 없는 경우에는 0를 return 합니다.

 

입출력 예

 

begin target words return
"hit" "cog" ["hot", "dot", "dog", "lot", "log", "cog"] 4
"hit" "cog" ["hot", "dot", "dog", "lot", "log"] 0

 


💡  나의 풀이

import java.util.*;

class Node {
    String word;
    int cnt;
    
    Node(String word, int cnt) {
        this.word = word;
        this.cnt = cnt;
    }
}

class Solution {
    public int solution(String begin, String target, String[] words) {
        Queue<Node> queue = new LinkedList<>();
        boolean[] visited = new boolean[words.length];
        
        queue.offer(new Node(begin, 0));
        
        while(!queue.isEmpty()) {
            Node node = queue.poll();
            
            if(node.word.equals(target))
                return node.cnt;
            
            for(int i=0; i<words.length; i++) {
                if(visited[i]) continue;
                if(changeable(node.word, words[i])) {
                    queue.offer(new Node(words[i], node.cnt+1));
                    visited[i] = true;
                }
            }
        }
        return 0;
    }
    
    private boolean changeable(String from, String to) {
        int diff = 0;
        
        for(int i=0; i<to.length(); i++) {
            if(from.charAt(i) != to.charAt(i))
                diff++;
        }
        
        if(diff == 1) return true;
        return false;
    }
}

BFS를 이용하여 풀이하였다. 

  • changeable 메서드는 두 String을 비교하여 한 글자만 다른 경우에 true를 리턴한다.
  • queue.poll로 큐에서 단어를 하나 꺼내고, words 중에서 changeable한 단어들을 모두 queue에 넣는다.

 

 


 

 

코딩테스트 연습 - 단어 변환

두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다. 1. 한 번에 한 개의 알파벳만 바꿀 수

programmers.co.kr

 

반응형