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

标签 java directed-graph adjacency-list weighted

此代码背后的想法是使用命令行参数创建一个图表: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/

相关文章:

java - Java 在哪个操作系统上运行是 "\n"不是有效的换行符序列?

java - 通过 ScopedPreferenceStore 在 FieldEditorPreferencePage 中设置默认值

java - 生成长椅随机座位表的最有效算法?

graph - 使用 CSV 属性设置链接长度、节点大小 d3

erlang - 如何复制 Erlang 有向图?

python - Python 中的二级内存索引表示

mysql - 以最佳方式存储分层数据 : NoSQL or SQL

java - Android Kinvey java.lang.NoClassDefFoundError

php - 如何在 html + php(codeIgniter) 中渲染一棵树

java - Yahoo Oauth 不一致 "Invalid Signature"