Swift Data Structure And Algorithm/Graph Algorithm
์ต๋จ ๊ฒฝ๋ก ์๊ณ ๋ฆฌ์ฆ - ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ(Dijkstra's Algorithm)
youngjaeLee1026
2022. 4. 16. 16:53
1. ๋ฌธ์
- ๊ฐ์ ์ ๊ฐ์ค์น๊ฐ ์กด์ฌํ๋ ๊ทธ๋ํ์ ์ต๋จ ๊ฒฝ๋ก๋ฅผ ์ฐพ๋ ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ์ ๊ตฌํ
2. ๋ฌธ์ ์ค๊ณ
- ์ฒ์ ๊ฐ ๋ ธ๋์ ๋ํ ์ต๋จ ๊ฒฝ๋ก๋ฅผ ํฐ ๊ฐ์ผ๋ก ์ด๊ธฐํ ํ๊ณ ,
- ์์์ ์ ์ต๋จ ๊ฒฝ๋ก ๊ฐ์ 0์ผ๋ก ์์ํ๊ณ , ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ๋ฅผ ํ ํ ์์์ ์ผ๋ก๋ถํฐ์ ์ต๋จ ๊ฒฝ๋ก ๊ฐ๊ณผ ์ธ์ ํ ์ ์ ๋ค์ ์ต๋จ ๊ฒฝ๋ก์ ํฉ ์ค ๋ ์์ ๊ฐ์ผ๋ก ์ ์ฅ
- ์ดํ ๋ค์ ์์ง ๋ฐฉ๋ฌธํ์ง ์์ ์ ์ ์ ๋ํ ์ต๋จ ๊ฒฝ๋ก ๊ฐ์ ์ต์๊ฐ์ ์ฐพ๊ณ ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ๋ฅผ ํจ
- ์ ๊ณผ์ ์ ๋ชจ๋ ์ ์ ์ ๋ํด ๋ฐ๋ณตํ๊ฒ ๋๋ฉด ์์์ ์ผ๋ก๋ถํฐ ๋ชจ๋ ์ ์ ์ ๋ํ ์ต๋จ ๊ฒฝ๋ก๋ฅผ ๊ตฌํ ์ ์์
3. ์ ์ฒด ์ฝ๋
//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
let start: Int = input.map { Int($0) }[2] ?? 0
let end: Int = input.map { Int($0) }[3] ?? 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 = inputData.map { Int($0) }[2] ?? 0
graph[a].edges.append(b)
graph[b].edges.append(a)
graph[a].costs.append(c)
graph[b].costs.append(c)
}
//MARK: - Process
result = dijkstra(N, start, end)
//MARK: - Output
print(result)
}
solution()
์ ์ฒด์ฝ๋๋ ์ฌ๊ธฐ์์ ํ์ธํ ์ ์์ต๋๋ค.