코딩테스트/Programmers

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

grove1212 2025. 8. 5. 18:03

문제

문제 설명

두 개의 단어 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

풀이

한 단계씩 거치면서 가장 빠른 경로를 찾으면 된다. dfs, bfs 둘다 사용 가능하다.

보통 최솟값을 찾는 문제는 bfs를 사용한다. 그치만 bfs를 어떻게 사용하는지 기억이 안나서... dfs를 사용해 풀이했다.

그리고 다른 사람의 풀이 중 bfs이용해 풀이한 부분을 가져왔다.

  1. 방문했는지 안했는지 체크하면서
  2. 현재의 단어와 한 개만 다른지 체크하면서
  3. target과 같으면 그때까지 몇 번 건넜는지 체크한다.
  4. (dfs이면) 1~3을 끝까지 반복하면서 최솟값을 찾는다.

bfs이면 4번을 할 필요 없이 가장 먼저 찾아지는 것이 최솟값이다.

내 풀이

import java.util.*;

class Solution {

    class Node{
        String word;
        int depth;
        Node(String w, int d) {
            this.word = w;
            this.depth = d;
        }
    }
    boolean[] visited;
    int count = Integer.MAX_VALUE;
    String targetValue;
    String[] wordList;
    public int solution(String begin, String target, String[] words) {
        visited = new boolean[words.length];
        targetValue = target;
        wordList = words;

        dfs(begin, 0);       

        return count == Integer.MAX_VALUE ? 0 : count;
    }

    void dfs(String word, int depth) {
        if(word.equals(targetValue)) {
            count = Math.min(count, depth);
            return;
        }

        for(int i = 0; i < wordList.length; i++) {
            if(visited[i]) continue;
            String compare = wordList[i];
            int cnt = 0;
            for(int j = 0; j < compare.length(); j++) {
                if(compare.charAt(j) != word.charAt(j)) cnt++;
            }

            if(cnt == 1) {
                visited[i] = true;
                dfs(compare, depth+1);
                visited[i] = false;
            }
        }
    }
}

다른 풀이

import java.util.LinkedList;
import java.util.Queue;

class Solution {

    static class Node {
        String next;
        int edge;

        public Node(String next, int edge) {
            this.next = next;
            this.edge = edge;
        }
    }

    public int solution(String begin, String target, String[] words) {
        int n = words.length, ans = 0;

        // for (int i=0; i<n; i++)
        //  if (words[i] != target && i == n-1) return 0;

        Queue<Node> q = new LinkedList<>();


        boolean[] visit = new boolean[n];
        q.add(new Node(begin, 0));

        while(!q.isEmpty()) {
            Node cur = q.poll();
            if (cur.next.equals(target)) {
                ans = cur.edge;
                break;
            }

            for (int i=0; i<n; i++) {
                if (!visit[i] && isNext(cur.next, words[i])) {
                    visit[i] = true;
                    q.add(new Node(words[i], cur.edge + 1));
                }
            }
        }

        return ans;
    }

    static boolean isNext(String cur, String n) {
        int cnt = 0;
        for (int i=0; i<n.length(); i++) {
            if (cur.charAt(i) != n.charAt(i)) {
                if (++ cnt > 1) return false;
            }
        }

        return true;
    }    
}