๋ฐ์ํ
๐ ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ (Dijkstra Algorithm)
1. ๊ฐ๋
๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ์ ๊ฐ์ค์น๊ฐ ์๋ ๊ทธ๋ํ์์ ํ ์ ์ ์์ ๋ค๋ฅธ ๋ชจ๋ ์ ์ ๊น์ง์ ์ต๋จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ๋ ์๊ณ ๋ฆฌ์ฆ์ด๋ค.
์์ ๊ฐ์ ์ด ์์ ๋ ์ฌ์ฉ ๊ฐ๋ฅํ๋ฉฐ, **์ฐ์ ์์ ํ(Heap)**๋ฅผ ์ด์ฉํ๋ฉด ๋น ๋ฅด๊ฒ ๊ณ์ฐํ ์ ์๋ค.
2. ์๋ ๋ฐฉ์ ์์ฝ
- ์์ ๋ ธ๋์์ ๊ฑฐ๋ฆฌ๋ฅผ 0์ผ๋ก ์ด๊ธฐํ, ๋๋จธ์ง๋ ๋ฌดํ๋๋ก ์ค์
- ์์ง ๋ฐฉ๋ฌธํ์ง ์์ ๋ ธ๋ ์ค ๊ฐ์ฅ ๊ฐ๊น์ด ๋ ธ๋ ์ ํ
- ์ ํํ ๋ ธ๋๋ฅผ ๊ธฐ์ค์ผ๋ก ์ธ์ ํ ๋ ธ๋์ ๊ฑฐ๋ฆฌ ์ ๋ฐ์ดํธ
- ๋ชจ๋ ๋ ธ๋๋ฅผ ๋ฐฉ๋ฌธํ ๋๊น์ง ๋ฐ๋ณต
3. C# ์์ ์ฝ๋ (์ฐ์ ์์ ํ ์ฌ์ฉ)
using System;
using System.Collections.Generic;
class Edge
{
public int To, Cost;
public Edge(int to, int cost)
{
To = to;
Cost = cost;
}
}
class Node : IComparable<Node>
{
public int Vertex, Distance;
public Node(int v, int d)
{
Vertex = v;
Distance = d;
}
public int CompareTo(Node other)
{
return Distance.CompareTo(other.Distance);
}
}
void Dijkstra(int start, List<Edge>[] graph, int[] dist)
{
int n = graph.Length;
bool[] visited = new bool[n];
for (int i = 0; i < n; i++) dist[i] = int.MaxValue;
dist[start] = 0;
var pq = new PriorityQueue<Node, int>();
pq.Enqueue(new Node(start, 0), 0);
while (pq.Count > 0)
{
pq.TryDequeue(out var current, out _);
int now = current.Vertex;
if (visited[now]) continue;
visited[now] = true;
foreach (var edge in graph[now])
{
int cost = dist[now] + edge.Cost;
if (cost < dist[edge.To])
{
dist[edge.To] = cost;
pq.Enqueue(new Node(edge.To, cost), cost);
}
}
}
}
๐ C# 10 ์ด์์์ PriorityQueue<TElement, TPriority> ์ฌ์ฉ ๊ฐ๋ฅ (System.Collections.Generic)
4. ์๊ฐ/๊ณต๊ฐ ๋ณต์ก๋
| ํญ๋ชฉ | ๋ณต์ก๋ |
| ์๊ฐ ๋ณต์ก๋ | O(E log V) (์ฐ์ ์์ ํ ์ฌ์ฉ ์) |
| ๊ณต๊ฐ ๋ณต์ก๋ | O(V + E) |
- V: ์ ์ ์
- E: ๊ฐ์ ์
5. ํน์ง
- ์์ ๊ฐ์ ์ด ์๋ ๊ฒฝ์ฐ์๋ง ์ฌ์ฉ ๊ฐ๋ฅ
- ๋จ์ผ ์์์ ๊ธฐ์ค ์ต๋จ ๊ฑฐ๋ฆฌ
- BFS๋ณด๋ค ๋ณต์กํ์ง๋ง ๋ ์ ํํ๊ณ ๋น ๋ฆ (๊ฐ์ค์น ํฌํจ ๊ฐ๋ฅ)
- ์ฝ๋ฉ ํ ์คํธ์์ ๊ทธ๋ํ ๋ฌธ์ ์ ์์ฃผ ๋ฑ์ฅ
6. ์์
์ ์ : 0, 1, 2, 3
๊ฐ์ : (0→1, 4), (0→2, 2), (2→1, 1), (1→3, 1), (2→3, 5)
์ถ๋ฐ: 0 → ๋์ฐฉ: ๋ชจ๋ ๋
ธ๋
์ต๋จ ๊ฑฐ๋ฆฌ: [0, 3, 2, 4]
7. ๋ง๋ฌด๋ฆฌ ์์ฝ
- ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ์ ๊ฐ์ฅ ๋๋ฆฌ ์ฐ์ด๋ ์ต๋จ ๊ฒฝ๋ก ์๊ณ ๋ฆฌ์ฆ
- ์์ ๊ฐ์ค์น๊ฐ ์๋ค๋ฉด ๋ฌด์กฐ๊ฑด ์ฌ์ฉ ๊ฐ๋ฅ
- ์ฐ์ ์์ ํ๋ฅผ ํ์ฉํ๋ฉด ์ฑ๋ฅ์ ํฌ๊ฒ ํฅ์์ํฌ ์ ์์
- ์ค์ ์์๋ BFS vs ๋ค์ต์คํธ๋ผ์ ์ ํ์ด ์ค์ํจ (๊ฐ์ค์น ์ ๋ฌด)
๋ฐ์ํ
'C#' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| C# - ํ๋ก์ด๋-์์ ์๊ณ ๋ฆฌ์ฆ (Floyd-Warshall) (1) | 2025.07.11 |
|---|---|
| C# - ๋ฒจ๋ง-ํฌ๋ ์๊ณ ๋ฆฌ์ฆ (Bellman-Ford Algorithm) vs ๋ค์ต์คํธ๋ผ (0) | 2025.07.11 |
| C# - ๊ทธ๋ํ ํ์ ์๊ณ ๋ฆฌ์ฆ โ DFS vs BFS (0) | 2025.07.11 |
| C# - ํ์ ์๊ณ ๋ฆฌ์ฆ ์ ๋ฆฌ โ ์ ํ ํ์ vs ์ด์ง ํ์ (0) | 2025.07.11 |
| C# - ์ ๋ ฌ ์๊ณ ๋ฆฌ์ฆ ๋น๊ต ์์ฝ (1) | 2025.07.11 |