youngjaeLee1026 2022. 4. 16. 16:59

1. 문제

스크린샷 2022-04-16 16 53 27

2. 입출력

스크린샷 2022-04-16 16 53 34

3. 입출력 예시

스크린샷 2022-04-16 16 53 41

4. 문제 설계

  • 그래프의 간선의 가중치가 없기 때문에 BFS로 최단 거리를 구해도 되지만, 다익스트라를 이용해서 해당 문제를 해결할 수 있음
  • 각 간선의 가중치를 1로 가정하고, 다익스트라 알고리즘을 적용하여 시작점부터 도착점까지의 최단 거리를 구함으로써 문제를 해결함

5. 전체 코드

//MARK: - 최단거리

//MARK: - Framework
import Foundation

//MARK: - Type
struct Graph {
    //MARK: - Property
    var edges: [Int]
    var costs: [Int]
    
    //MARK: - Initializer
    init() {
        self.edges = []
        self.costs = []
    }
}

//MARK: - Variable
var graph: [Graph] = []
var visited: [Bool] = []

//MARK: - Function
func dijkstra(_ N: Int, _ start: Int, _ end: Int) -> Int {
    var distances: [Int] = Array(repeating: 987987987, count: N + 10)
    distances[start] = 0
    
    for _ in 0..<N {
        var minCost, minIndex: Int
        minCost = 987987987
        minIndex = -1
        
        for j in 0..<N {
            if !visited[j] && minCost > distances[j] {
                minCost = distances[j]
                minIndex = j
            }
        }
        visited[minIndex] = true
        
        for j in 0..<graph[minIndex].edges.count {
            let y: Int = graph[minIndex].edges[j]
            let cost: Int = graph[minIndex].costs[j]
            
            if distances[y] > distances[minIndex] + cost {
                distances[y] = distances[minIndex] + cost
            }
        }
    }
    
    return distances[end]
}

func solution() -> Void {
    //MARK: - Input
    guard let input: [String] = readLine()?.components(separatedBy: " ") else { return }
    let N: Int = input.map { Int($0) }[0] ?? 0
    let M: Int = input.map { Int($0) }[1] ?? 0
    var result: Int = 0
    
    graph = Array(repeating: Graph(), count: N + 10)
    visited = Array(repeating: false, count: N + 10)
    
    for _ in 0..<M {
        guard let inputData: [String] = readLine()?.components(separatedBy: " ") else { return }
        let a: Int = inputData.map { Int($0) }[0] ?? 0
        let b: Int = inputData.map { Int($0) }[1] ?? 0
        let c: Int = 1
        
        graph[a].edges.append(b)
        graph[b].edges.append(a)
        graph[a].costs.append(c)
        graph[b].costs.append(c)
    }
    guard let data: [String] = readLine()?.components(separatedBy: " ") else { return }
    let start: Int = data.map { Int($0) }[0] ?? 0
    let end: Int = data.map { Int($0) }[1] ?? 0
    
    //MARK: - Process
    result = dijkstra(N, start, end)
    
    //MARK: - Output
    print(result)
}
solution()

 

전체코드는 여기에서 확인할 수 있습니다.