gpt4 book ai didi

java - 当我尝试打印加权有向图(调整列表)的内容时输出错误

转载 作者:行者123 更新时间:2023-12-01 10:34:22 24 4
gpt4 key购买 nike

此代码背后的想法是使用命令行参数创建一个图表:AB5、BC4、CD8、DC8、DE6、AD5、CE2、EB3、AE7

第一个字母是源,第二个字母是目的地。最后一个数字是边权重。我感觉我输入正确,但我的打印方法已关闭。

这是我运行程序时得到的输出:

A --> E weight: 3 --> D weight: 6 --> B weight: 4

B --> C weight: 2

C --> E weight: 3 --> D weight: 6

D --> E weight: 3 --> C weight: 2

E --> B weight: 4

如您所见:

A --> E 应该是 7。

A --> D 应该是 5。

等等...

我做错了什么?

package graphs;

class Neighbor{
public int vNum;
public int weight;
public Neighbor next;

//Constructor
Neighbor(int num, int weight, Neighbor nbr){
this.vNum = num;
this.weight = weight;
next = nbr;
}
}

class Vertex{
char v;
Neighbor adj;

//Constructor
Vertex(char vertex, Neighbor neighbors){
this.v = vertex;
this.adj = neighbors;
}
}

public class WDiGraph {
Vertex[] adjList;

//constructor
public WDiGraph(int v, String[] edges){
adjList = new Vertex[v];

//Vertices
for(int i = 0; i < v; i++)
adjList[i] = new Vertex((char)(i + 65), null); //ascii value arithmetic

//Edges
for(int i = 0; i < edges.length; i++){
int src = edges[i].charAt(0) - 65;
int dest = edges[i].charAt(1) - 65;
int weight = edges[i].charAt(2) - 48;
adjList[src].adj = new Neighbor(dest, weight, adjList[src].adj);
}
}

public void print(){
System.out.println();

for(int i = 0; i < adjList.length; i++){
System.out.print(adjList[i].v);

for(Neighbor nbr = adjList[i].adj; nbr != null; nbr = nbr.next)
System.out.print(" --> " + adjList[nbr.vNum].v + " weight: " + adjList[nbr.vNum].adj.weight);

System.out.println("\n");
}
}

public static void main(String[] args) {
WDiGraph wdg = new WDiGraph(5, args); //Instantiates a Weighted DiGraph object with 5 vertices
wdg.print();
}

}

最佳答案

按如下方式更改行打印粗细:

来自

System.out.print(" --> " + adjList[nbr.vNum].v + " weight: " + 
adjList[nbr.vNum].adj.weight);

System.out.print(" --> " + adjList[nbr.vNum].v + " weight: " + nbr.weight);

关于java - 当我尝试打印加权有向图(调整列表)的内容时输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34867615/

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