Skip to content
Snippets Groups Projects
Verified Commit b8e8d433 authored by Dmytro Bogatov's avatar Dmytro Bogatov :two_hearts:
Browse files

Add docs to portals.

parent 59d9dbd8
Branches
No related tags found
No related merge requests found
......@@ -35,40 +35,50 @@ namespace CodingInterview.School
/// Returns the minmum amount of money needed to get all plannets connected.
/// </summary>
/// <param name="costs">the costs of building a portal on each planet (index is a planet)</param>
/// <param name="connections">pairs of indices representing planets which already have portals between them</param>
/// <param name="connections">pairs of indices representing planets which already have portals between them (here indexaton starts from 1)</param>
/// <returns>the minmum amount of money needed to get all plannets connected</returns>
public int Solve(int[] costs, (int from, int to)[] connections)
{
// create planets given costs
var planets = new Planet[costs.Length];
for (var planet = 0; planet < costs.Length; planet++)
{
planets[planet] = new Planet { Cost = costs[planet] };
}
// setup connections
foreach (var connection in connections)
{
planets[connection.from - 1].Neighbors.Add(planets[connection.to - 1]);
planets[connection.to - 1].Neighbors.Add(planets[connection.from - 1]);
}
// go over all planets in a BFS manner
var minCosts = new List<int>();
for (var planet = 0; planet < costs.Length; planet++)
{
// skip visited planets
if (planets[planet].Visited)
{
continue;
}
// initialize BFS queue with the initial (unvisited) planet
var minCost = Int32.MaxValue;
var bfsQueue = new Queue<Planet>();
bfsQueue.Enqueue(planets[planet]);
// until entire cluster is traversed
while (bfsQueue.Count > 0)
{
var current = bfsQueue.Dequeue();
// skip visited
if (!current.Visited)
{
// update min cost in the cluster
minCost = Math.Min(current.Cost, minCost);
// don't go here again
current.Visited = true;
// add not visited neighbors to the queue
foreach (var neighbor in current.Neighbors)
{
if (!neighbor.Visited)
......@@ -78,14 +88,16 @@ namespace CodingInterview.School
}
}
}
if (minCost != Int32.MaxValue)
{
// remember min cost of the cluster
minCosts.Add(minCost);
}
}
// find the smallest of all min costs
var minOfMin = minCosts.Min();
// if T is the number of clusters, the final cost is building T - 1 portals in the cheapest cluster on its cheapest planet,
// then building a portal on a cheapest planet on each of the other clusters
return minOfMin * (minCosts.Count - 1) + (minCosts.Sum() - minOfMin);
}
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment