1. 生成连通图 (至少有一颗生成树)
2.生成连通图 (至少有一颗生成树,或者更多)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Algorithm
{
public class CollectedGraph
{
/// <summary>
/// Build a random collected Graph.
/// Every node has at leave one node to collect
/// </summary>
/// <param name="NodeCount"></param>
/// <returns></returns>
public Double[,] BuildRandom(int NodeCount)
{
Double[,] map = new Double[NodeCount, NodeCount];
HashSet<string> edges = new HashSet<string>();
for (int i = 0; i < NodeCount; i++)
for (int j = 0; j < NodeCount; j++)
{
if (i == j)
{
map[i, j] = 0;
}
else
{
map[i, j] = double.MaxValue;
}
}
Random rand = new Random();
List<int> S = new List<int>();
List<int> U = new List<int>();
for (int k = 1; k < NodeCount; k++)
{
U.Add(k);
}
S.Add(0);
while (U.Count > 0)
{
int rndFrom = rand.Next(0, S.Count);
int rndTo = rand.Next(0, U.Count);
int from = S[rndFrom];
int to = U[rndTo];
S.Add(to);
U.Remove(to);
map[from, to] = rand.Next(1000);
edges.Add(from.ToString() + "-" + to.ToString());
}
return map;
}
/// <summary>
/// Build a random collected Graph.
/// More node are collected .
/// like a real graph.
/// </summary>
/// <param name="NodeCount"></param>
/// <returns></returns>
public Double[,] BuildRandomMore(int NodeCount)
{
Double[,] map = BuildRandom(NodeCount);
Random rand = new Random();
for (int i = 0; i < NodeCount; i++)
{
int from = rand.Next(0, NodeCount);
int to = rand.Next(from, NodeCount);
map[from, to] = rand.Next(0, 1000);
}
return map;
}
}
}
Unit Test:
/// <summary>
///A test for BuildRandom
///</summary>
[TestMethod()]
public void BuildRandomTest()
{
CollectedGraph target = new CollectedGraph(); // TODO: Initialize to an appropriate value
int NodeCount = 1000;
double[,] map;
//map = target.BuildRandom(NodeCount);
map = target.BuildRandomMore(NodeCount);
List<string> edges;
List<double> weights;
List<int> tree = target.BuildSpanningTree(map, out edges, out weights);
ShortestPath pathTest = new ShortestPath();
Double[] distanct;
Dictionary<int, string> actual = pathTest.Build(map, out distanct);
}