11404 swift - 플로이드

2024. 2. 5. 19:44🐣/BOJ

플로이드 워셜 알고리즘 사용

 

[그래프] 플로이드 워셜(Floyd-Warshall Algorithm)

플로이드 워셜(Floyd-Warshall Algorithm) 컴퓨터 과학에서 플로이드-워셜 알고리즘(Floyd-Warshall Algorithm)은 변의 가중치가 음이거나 양인 (음수 사이클은 없는) 가중 그래프에서 최단 경로들을 찾는 알고

chanhhh.tistory.com

중간노드를 거쳐서 갈 수 있는 경우를 고려하여 3중 for문으로 코드를 작성합니다.

import Foundation

var n = Int(readLine()!)!
var cost = Array(repeating: Array(repeating: 987654321, count: n), count: n)
for _ in 0..<Int(readLine()!)! {
    let abc = readLine()!.split{$0==" "}.map{Int(String($0))!}
    let (a, b, c) = (abc[0], abc[1], abc[2])
    cost[a-1][b-1] = min(c, cost[a-1][b-1])
}

for k in 0..<n {
    for i in 0..<n {
        for j in 0..<n {
            if (i==j) { cost[i][j] = 0 }
            cost[i][j] = min(cost[i][j], cost[i][k]+cost[k][j])
        }
    }
}

for result in cost {
    let validator = result.map { $0 == 987654321 ? 0 : $0 }
    print(validator.map{String($0)}.joined(separator: " "))
}

 

 

 

'🐣 > BOJ' 카테고리의 다른 글

14171 swift - Cities and States  (0) 2024.03.06
1967 swift - 트리의 지름  (0) 2024.02.07
9935 swift - 문자열 폭발  (0) 2024.02.02
9663 swift - N-Queen  (0) 2023.06.12
11444 swift - 피보나치 수 6  (0) 2023.06.11