View

https://school.programmers.co.kr/learn/courses/30/lessons/43163?language=java 

 

프로그래머스

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

programmers.co.kr

📚 문제

문제 설명

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

 

📝 문제 해결

  • bfs (너비 우선 탐색법)

begin 단어를 큐에 넣어주고 words 단어 중 begin과 한 개의 알파벳만 다르고 아직 방문하지않은 단어를 큐에 넣어주고 count+1 해준 뒤 방문처리한다. 큐의 단어가 target과 같은 경우, count를 return해줌

 

  • dfs (깊이 우선 탐색법)

words 단어 중 begin과 한 개의 알파벳만 다르고 아직 방문하지않은 단어를 방문처리해주고 count+1 후 재귀 호출해준다. (모든 경우의 수를 탐색하기 위해 visitd[i] = false로 되돌려줘야함)

넘겨준 begin값이 target과 같은 경우 answer를 최솟값으로 갱신해준다.

 

💻 코드

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

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

class Solution {
    int answer = Integer.MAX_VALUE;
    boolean[] visited;
    
    public int solution(String begin, String target, String[] words) {
        visited = new boolean[words.length];
        
        return bfs(begin, target, words);
        
        /*
        dfs(begin, target, words, 0);
        if(answer == Integer.MAX_VALUE){
            return 0;
        }
        return answer;
        */
    }
    
    public int bfs(String begin, String target, String[] words){
        Queue<Node> que = new LinkedList<>();
        que.add(new Node(begin, 0));
        
        while(!que.isEmpty()){
            Node cur = que.poll();
            
            if(cur.word.equals(target)) return cur.count;
            
            for(int i=0; i<words.length; i++){
                int match = 0;
                for(int j=0; j<begin.length(); j++){
                    if(cur.word.charAt(j) == words[i].charAt(j)) match++;
                }
                
                if(!visited[i] && match == begin.length()-1){
                    que.add(new Node(words[i], cur.count+1));
                    visited[i] = true;
                }
            }
        }
        
        return 0;
    }
    
    public void dfs(String begin, String target, String[] words, int count){
        if(begin.equals(target)){
            answer = Math.min(answer, count);
            return;
        }
        
         for(int i=0; i<words.length; i++){
             if(visited[i])  continue;
                
             
             int match = 0;
             for(int j=0; j<begin.length(); j++){
                 if(begin.charAt(j) == words[i].charAt(j))  match++;
             }
             
             if(match == begin.length()-1){
                 visited[i] = true;
                 dfs(words[i], target, words, count+1);
                 visited[i] = false;
             }
         }
    }
}
728x90
Share Link
reply
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31