我编写了一个函数,它将有向图作为邻接矩阵返回。函数需要两个参数:节点的数量和边的数量。首先,节点被放置并立即连接到图形。当所有节点被添加时,随机边被创建,直到所有边被放置。
代码:
public int[,] GenerateMatrix(int Nodes, int Edges)
{
if (Edges < Nodes - 1) throw new Exception("Too few edges");
if (Edges > Nodes * (Nodes - 1)) throw new Exception("Too many edges");
int[,] adjacencyMatrix = new int[Nodes, Nodes];
// Gives every cell a value of zero
for (int y = 0; y < Nodes; y++)
{
for (int x = 0; x < Nodes; x++)
{
adjacencyMatrix[x, y] = 0;
}
}
int placedEdges = 0;
for (int i = 1; i < Nodes; i++)
{
// produce edge between rnd(0, amountofnodes) to new node
int fromVertex = random.Next(0, i);
int weight = random.Next(1, 10);
adjacencyMatrix[i, fromVertex] = weight;
placedEdges++;
}
while (placedEdges < Edges)
{
int fromVertex = random.Next(0, Nodes);
int weight = random.Next(1, 10);
int targetVertex = random.Next(0, Nodes);
while (targetVertex == fromVertex || adjacencyMatrix[targetVertex, fromVertex] != 0) //|| adjacencyMatrix[fromVertex, targetVertex] != 0)// tredje condition tar bort parallella kanter
{
fromVertex = random.Next(0, Nodes);
targetVertex = random.Next(0, Nodes);
}
adjacencyMatrix[targetVertex, fromVertex] = weight;
placedEdges++;
}
return adjacencyMatrix;
}发布于 2021-01-18 12:51:14
您可以描述代码要完成的任务:
在代码中这样做,使用对您有用的工具支持。MS在XML狂欢上,强力氧原目前有一个.nl域。
省略每个单元格的值为零:
数值数组元素的默认值设置为零,和引用元素设置为null。
您使用节点以及顶点- 彼得·克拉拉已经评估混合来自和目标。
对于一致伪随机的非负数,直到某些maxValue调用int Random.Next(int maxValue)。
每一个边从第一个循环“点向下”,引入一个非均匀性。
当选择一个已经有节点-1传出边的fromVertex时,while-loop不会终止。
不管怎么说,当节点^3/2边有更多的时候,希望有很多次通过这个循环。
(特雷杰·威克雷·波维克尔anti__parallella kanter)
(不使用反平行边将需要考虑在初始(未注释!)(距离检查)
https://codereview.stackexchange.com/questions/254868
复制相似问题