gpt4 book ai didi

c# - 在 C# 中创建图形类

转载 作者:行者123 更新时间:2023-12-05 07:15:52 24 4
gpt4 key购买 nike

我的任务是在 C# 中创建 Graph 类,它具有以下属性:

private List<string> vertices;
private List<List<int>> adjacencyMatrix;
private int n;

n 是节点数,我相信其余部分不言自明。该类还应该有两个如下所示的方法:

添加(字符串顶点){}

AddConnection(string vertex1, string vertex2, int value){}

至此,我想通了Add方法(假设0代表顶点之间没有连接):

public void Add(string vertex)
{
this.vertices.Add(vertex);
List<int> temp = new List<int>();
foreach(List<int> element in this.adjacencyMatrix)
{
element.Add(0);
}
foreach(string element in vertices)
{
temp.Add(0);
}
this.adjacencyMatrix.Add(temp);

this.n++;
}

但是我还是不知道怎么添加连接。任何帮助将不胜感激

最佳答案

好吧,尽管有负面评论,我还是设法解决了它。我知道这种方法没有多大意义,但我没有选择它。如果有人感兴趣,请在 AddAddConnection 方法下方,另外使用 SaveMatrix 方法将其很好地写入 txt 文件。

   public void Add(string vertex)
{
this.vertices.Add(vertex);
List<int> temp = new List<int>();

foreach(List<int> element in this.adjacencyMatrix)
{
element.Add(0);
}
foreach(string element in vertices)
{
temp.Add(0);
}
this.adjacencyMatrix.Add(temp);

this.n++;
}

public void AddConnection(string vertex1, string vertex2, int value)
{
if(this.vertices.Contains(vertex1) && this.vertices.Contains(vertex2))
{
int index1= this.vertices.IndexOf(vertex1);
int index2 = this.vertices.IndexOf(vertex2);

this.adjacencyMatrix[index1][index2] = value;
this.adjacencyMatrix[index2][index1] = value;
}
else
{
Console.WriteLine("Graph doesn't contain passed vertex/vertices.");
}
}

public void SaveMatrix(string filename)
{
// save matrix with nice formatting
// works if the names of the vertices are shorter than 16 chars and if edge weights are shorter than 100 (and positive)
try
{
StreamWriter sw = new StreamWriter(filename);
sw.Write("".PadRight(16)); // pad a string with white spaces to get exactly the specified length in chars
foreach (string s in vertices) sw.Write(s.PadRight(16)); // write first row with names
sw.WriteLine();
int counter = 0;
foreach (List<int> column in adjacencyMatrix) // other rows
{
sw.Write(vertices[counter].PadRight(16)); // start with vertex name
counter++;
foreach (int i in column)
{
if (i >= 10) sw.Write(i + "".PadRight(15)); // two digits
else if (i > 0) sw.Write("0" + i + "".PadRight(15)); // one digit
else sw.Write("--" + "".PadRight(15)); // no connection
}
sw.WriteLine();
}
sw.Close();
}
catch (IOException e)
{
Console.WriteLine("Error - the file could not be read");
Console.WriteLine(e.Message);
}
}

关于c# - 在 C# 中创建图形类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59453221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com