Prim 알고리즘은 하나의 정점을 시작으로 최소 비용 간선을 하나씩 선택해 트리 형태로 확장해가는 방식의 최소 스패닝 트리(MST) 알고리즘이다.
| 항목 | Prim | Kruskal |
|---|---|---|
| 기준 | 현재 트리 내 정점들 | 전체 간선 목록 |
| 사이클 방지 | 정점 방문 여부로 판단 | Disjoint Set 사용 |
| 자료구조 | 우선순위 큐 | 간선 리스트, Disjoint Set |
💡 다익스트라와 유사하지만 기준점이 다르다:
EMPTY), 짝수 좌표에 벽(WALL)을 배치.for (int32 y = 0; y < _size; y++) {
for (int32 x = 0; x < _size; x++) {
_tile[y][x] = (x % 2 == 0 || y % 2 == 0) ? TileType::WALL : TileType::EMPTY;
}
}
map<Pos, vector<CostEdge>> edges;
for (int32 y = 0; y < _size; y++) {
for (int32 x = 0; x < _size; x++) {
if (x % 2 == 0 || y % 2 == 0) continue;
Pos u = Pos{ y, x };
if (x < _size - 2) {
Pos v = Pos{ y, x + 2 };
int cost = rand() % 100;
edges[u].push_back({ cost, v });
edges[v].push_back({ cost, u });
}
if (y < _size - 2) {
Pos v = Pos{ y + 2, x };
int cost = rand() % 100;
edges[u].push_back({ cost, v });
edges[v].push_back({ cost, u });
}
}
}
edges는 인접 리스트 형태로 간선 정보를 저장priority_queue<CostEdge> pq;
map<Pos, bool> added;
map<Pos, Pos> parent;
map<Pos, int32> best;
for (int32 y = 0; y < _size; y++)
for (int32 x = 0; x < _size; x++) {
Pos p = { y, x };
best[p] = INT32_MAX;
added[p] = false;
}
Pos start = { 1, 1 };
pq.push({ 0, start });
best[start] = 0;
parent[start] = start;
while (!pq.empty()) {
CostEdge edge = pq.top();
pq.pop();
Pos v = edge.vtx;
if (added[v]) continue;
added[v] = true;
// 통로를 뚫는다
{
int y = (parent[v].y + v.y) / 2;
int x = (parent[v].x + v.x) / 2;
_tile[y][x] = TileType::EMPTY;
}
for (auto& e : edges[v]) {
if (added[e.vtx]) continue;
if (e.cost > best[e.vtx]) continue;
best[e.vtx] = e.cost;
parent[e.vtx] = v;
pq.push(e);
}
}