본문 바로가기

Algorithm/DFS,BFS

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

문제 설명

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

풀이

Visited 배열은 방문의 목적을 담고 있다. 해당 단어를 한번 방문하게 되면 방문에 대한 정보를 체크하게 되고 이후 다시 한번 방문 하는 것을 막고자 하는 목적이 있다. 이렇게 하는이유는 루프에 갇혀서 못나오는 상황을 막고자 하는 의도를 담고있으며 totalcount는 .... 지금 보니 그냥 조건 처리하여 계산하는게 좀 더 깔끔할 것 같다. 그냥 int값의 최고 값을 초기 값으로 설정하고 풀이에 임하였을 뿐... 
HashSet을 이용하여 단어별 중복을 거르고 변환 대상의 단어가 들어있는지 확인하는 과정을 거친 후 없다면 0을 리턴하고 있다면 DFS를 수행!!! 

import java.util.HashSet;


public class Solution {
    static String[] wordset;
    static boolean[] visited;
    static String strTarget;
    static int totalcount;
    public int solution(String begin, String target, String[] words){
        int answer = 0;
        HashSet<String>isPossible = new HashSet<>();

        visited = new boolean[words.length];
        strTarget= target;
        totalcount = 2147483647;
        int count = 0;
        if(begin.equals(target)){
            return 0;
        }
        for(String tmp : words){
            if(begin.equals(tmp)){
                continue;
            }
            isPossible.add(tmp);
        }
        wordset = isPossible.stream().toArray(String[]::new);
        if(!isPossible.contains(target)){
            return 0;
        }else{
            dfs(0,begin);
        }
        return totalcount;

    }

    private void dfs(int i, String begin) {
        if(begin.equals(strTarget)){
            if(totalcount>i){
                totalcount = i;
            }
            return;

        }else{
            for(int counting = 0;counting<wordset.length;counting++){
                if(!visited[counting] && isChanged(begin,wordset[counting])){
                    visited[counting] = true;
                    dfs(i+1,wordset[counting]);
                    visited[counting] = false;
                }
            }
        }
    }

    private boolean isChanged(String begin, String s) {
        int count =0;
        for(int i=0;i<begin.length();i++){
            if(begin.charAt(i)!=s.charAt(i)){
                count++;
                if(count>1){
                    return false;
                }
            }
        }
        return true;
    }
}