Skip to content

Commit aed406e

Browse files
Merge pull request #133 from HmmCorn/oliver
플로이드
2 parents 05082b1 + 3b556ba commit aed406e

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
let INF = 100_000 * 100 + 1
2+
let n = Int(readLine()!)!
3+
let m = Int(readLine()!)!
4+
5+
// 인접리스트
6+
var graph: [[(node: Int, weight: Int)]] = Array(repeating: [], count: n+1)
7+
for _ in 0..<m {
8+
let line = readLine()!.split(separator: " ").compactMap { Int($0) }
9+
let (a, b, c) = (line[0], line[1], line[2])
10+
11+
graph[a].append((node: b, weight: c))
12+
}
13+
14+
// dist 초기화
15+
var dist: [[Int]] = Array(repeating: Array(repeating: INF, count: n+1), count: n+1)
16+
for i in 1...n {
17+
dist[i][i] = 0
18+
}
19+
20+
// graph 순회하면서 dist행렬 채우기
21+
for i in 1...n {
22+
for edge in graph[i] {
23+
let destination = edge.node
24+
let weight = edge.weight
25+
26+
dist[i][destination] = min(weight, dist[i][destination])
27+
}
28+
}
29+
30+
// 플로이드
31+
for k in 1...n {
32+
for i in 1...n {
33+
for j in 1...n {
34+
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
35+
}
36+
}
37+
}
38+
39+
// 출력
40+
for i in 1...n {
41+
var row: [String] = []
42+
for j in 1...n {
43+
if dist[i][j] == INF {
44+
row.append("0")
45+
} else {
46+
row.append(String(dist[i][j]))
47+
}
48+
}
49+
print(row.joined(separator: " "))
50+
}

0 commit comments

Comments
 (0)