Search code examples
javadirected-graphadjacency-listweighted

Wrong output when I try to print out contents of Weighted Directed Graph (adj list)


The idea behind this code is to create a graph using command line arguments: AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7

First letter is the source and the second letter is the destination. The last number is the edge weight. I feel like I'm inputting it correctly but my print method is off.

Here is the output I get when I run the program:

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

As you can see:

A --> E should be 7.

A --> D should be 5.

etc...

What am I doing wrong?

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();
    }

}

Solution

  • Change the line printing weight as follows:

    From

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

    To

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