본문 바로가기

코딩 테스트/DFS

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

문제

두 개의 단어 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 합니다.

풀이 과정

1. begin 단어의 인덱스별로 DFS

2. words에서 변환 가능한 단어가 있다면 해당 단어를 begin으로 변경 후 다시 DFS 반복

3. begin == target이라면 answer와 count 비교 후 최소 값 저장

 

코드

class Solution {
    var answer = 0
    fun solution(begin: String, target: String, words: Array<String>): Int {
        val check = Array(words.size){false}
        
        for(i in begin.indices){
            // 바꿀 단어 인덱스 별로 탐색
            change(i, begin, target, words, check)
        }
        
        return answer
    }
    
    fun change(index: Int, begin: String, target: String, words: Array<String>, c: Array<Boolean>){
        if(begin == target){
            answer = if(answer == 0) c.count{it == true} else Math.min(answer, c.count{it == true})
            return
        }
        
        val check = c.copyOf()
        // 변환할 인덱스 제외하고 합체 ex) hot의 o를 바꾼다면 ht
        val newBegin = begin.substring(0, index) + begin.substring(index+1, begin.length)
        
        // 변환 가능한 words 탐색
        words.forEachIndexed{ wordIndex, it ->
            if(!check[wordIndex]){
                // 변환한 인덱스 제외하고 합체
                val newWord = it.substring(0, index) + it.substring(index+1, begin.length)
                // 변환 가능하다면 
                if(newBegin == newWord){
                    check[wordIndex] = true

                    for(i in it.indices){
                        change(i, it, target, words, check)
                    }
                    check[wordIndex] = false
                }   
            }
        }
    }
}