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

이창형·2023년 5월 9일
0

코드

import Foundation

func solution(_ begin:String, _ target:String, _ words:[String]) -> Int {
    var visited = Array(repeating: false, count: words.count)
    var count = 0
    var queue = [(String, Int)]()
    
    queue.append((begin,0))
    
    if !words.contains(target) {
        return 0
    }
    
    func check(_ str: String, _ str2: String) -> Bool {
        var a = str.map{String($0)}
        var b = str2.map{String($0)}
        var count = 0
        
        for i in 0..<a.count {
            if a[i] != b[i] {
                count += 1
            }
        }
        
        if count > 1 {
            return false
        }
    
        return true
    }
    
    while !queue.isEmpty {
        var now = queue.removeFirst()
        
        if now.0 == target {
            return now.1
        }
        
        for i in 0..<words.count {
            if check(words[i], now.0) && !visited[i] {
                visited[i] = true
                queue.append((words[i], now.1 + 1))
            }
        }
    }
    
    return 0
}

회고

  • 기본적인 bfs 문제였다
  • 3단계 풀려서 기분이 좋다
  • bfs로 풀어야겠다는 생각이 조금만 더 빨리 났으면 좋겠다 !
profile
iOS Developer

0개의 댓글