Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions WEEK11/백준_11404_플로이드/raven.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
let n = Int(readLine()!)!
let m = Int(readLine()!)!
var graph = Array(repeating:Array(repeating: Int.max, count: n + 1), count: n + 1)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

그래프의 자기 자신으로 가는 경로(i == j)의 비용은 항상 0입니다. 이를 3중 반복문 내부에서 매번 확인하는 대신, 초기화 시점에 미리 0으로 설정하는 것이 효율적입니다.

Suggested change
var graph = Array(repeating:Array(repeating: Int.max, count: n + 1), count: n + 1)
var graph = Array(repeating: Array(repeating: Int.max, count: n + 1), count: n + 1)
for i in 1...n { graph[i][i] = 0 }


for _ in 0..<m {
let component = readLine()!.split(separator: " ").compactMap {Int($0)}
let start = component[0]
let end = component[1]
let cost = component[2]

// 중복 있음;; 최솟값만 넣기
if graph[start][end] > cost { graph[start][end] = cost }
}

// for i in 1..<graph.count {
// let row = graph[i].map { $0 == Int.max ? "-": String($0) }.joined(separator: " ")
// print(row)
// }

// 경유
for k in 1...n {
// 시작
for i in 1...n {
// 도착
for j in 1...n {
if i == j { graph[i][j] = 0 }
if graph[i][k] != Int.max && graph[k][j] != Int.max {
let cost = graph[i][k] + graph[k][j]
if graph[i][j] > cost {
graph[i][j] = cost
}
}
}
Comment on lines +25 to +33
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

i == j인 경우를 처리하는 로직을 초기화 단계로 옮겼으므로, 반복문 내부에서는 최단 경로를 갱신하는 로직만 남겨둘 수 있습니다. min 함수를 사용하면 코드를 더 간결하게 작성할 수 있습니다.

        for j in 1...n {
            if graph[i][k] != Int.max && graph[k][j] != Int.max {
                graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j])
            }
        }

}
}

// 만약, i에서 j로 갈 수 없는 경우에는 그 자리에 0을 출력한다.
for i in 1..<graph.count {
graph[i].removeFirst()
let row = graph[i].map { $0 == Int.max ? "0" : String($0) }.joined(separator: " ")
print(row)
Comment on lines +38 to +41
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

removeFirst()는 배열의 모든 요소를 앞으로 한 칸씩 당기는 작업이므로 $O(N)$의 시간 복잡도를 가집니다. 또한 원본 배열을 수정하게 됩니다. 슬라이싱(graph[i][1...n])을 사용하면 원본을 유지하면서도 효율적으로 필요한 범위만 출력할 수 있습니다.

Suggested change
for i in 1..<graph.count {
graph[i].removeFirst()
let row = graph[i].map { $0 == Int.max ? "0" : String($0) }.joined(separator: " ")
print(row)
for i in 1...n {
let row = graph[i][1...n].map { $0 == Int.max ? "0" : String($0) }.joined(separator: " ")
print(row)

}