The Architect
You are the lead dungeon architect at a game studio. Your procedural generation system has placed n rooms randomly across the map. You need to connect all rooms with corridors so players can explore every room — but carving corridors through rock is expensive.
Given n rooms numbered 0 to n-1 and a list of possible corridors [u, v, cost] representing the construction cost to connect rooms u and v, find the minimum total construction cost to connect all rooms. Corridors are undirected.
If it is impossible to connect all rooms (disconnected map), return -1.
Example 1
(4, [[0,1,1],[1,2,1],[0,2,1],[2,3,10]])12Take corridors (0,1) cost 1, (1,2) cost 1 — adding (0,2) would create a cycle. Must add (2,3) cost 10 to reach room 3. Total: 12.
Example 2
(4, [[0,1,5],[2,3,5]])-1Rooms 0-1 and rooms 2-3 are separate islands with no corridor between them. Impossible to connect all rooms.
Example 3
(3, [[0,1,1],[1,2,100],[0,2,2]])3Take (0,1) cost 1 and (0,2) cost 2 = total 3. Skip the expensive (1,2) cost 100 corridor.
- ›1 <= n <= 1000
- ›0 <= len(corridors) <= 10000
- ›1 <= cost <= 10^6
- ›Corridors are undirected
- ›No self-loops
Loading question…