chickenmomosTarriwale
chickenmomosTarriwale

Reputation: 43

My graph code not running and neither throwing any error?

I am trying to implement a graph. I am not able to understand why my code is not working. I tried to look where is it getting wrong but cannot figure out and my ide not giving any error also. I am beginner can someone tell me where am i getting and why ? I am posting my code below.

import java.util.*;
class Graph {

    private int V;
    private LinkedList<Integer>[] adjList ;

    Graph(int V) {

        adjList = new LinkedList[V];

        for(int i=0 ; i<V ; i++) {
            adjList[i] = new LinkedList<Integer>();
        }
    }

    public void addEdge(int v, int w) {
        adjList[v].add(w);
    }

    public void printGraph(Graph graph) {
        for(int i=0 ; i<graph.V ; i++) {
            for(Integer pCrawl : graph.adjList[i]){
                System.out.print(pCrawl+" ");
            }
        }
    }

    public static void main(String[] args) {
        Graph g = new Graph(4); 

        g.addEdge(0, 1); 
        g.addEdge(0, 2); 
        g.addEdge(1, 2); 
        g.addEdge(2, 0); 
        g.addEdge(2, 3); 
        g.addEdge(3, 3); 

        g.printGraph(g);
    }
}

Upvotes: 0

Views: 60

Answers (3)

Nehorai Elbaz
Nehorai Elbaz

Reputation: 2452

You need ti initilaize V like: this.V = V; inside the constructor. another thing the method printGraph does not neet to recieve Graph varibale and you can write it like:

public void printGraph() {
    for(int i=0 ; i<V ; i++) 
        for(Integer pCrawl : adjList[i])
            System.out.print(pCrawl+" ");              
}

Upvotes: 1

khelwood
khelwood

Reputation: 59113

Your Graph class has a field called V. There is also a parameter int V that is received by your constructor. They are not the same variable. Unless you initialise the field V, it will be zero.

So this loop

for(int i=0 ; i<graph.V ; i++)

exits immediately.

The way to set the field V to the received variable V in your constructor is by adding

this.V = V;

inside your constructor.

Upvotes: 1

user5809739
user5809739

Reputation:

You need to print a entire line to manage the y-axis and limit i by the count of elements in your adjList:

    public void printGraph(Main graph) {
        for(int i=0 ; i<graph.adjList.length ; i++) {
            for(Integer pCrawl : graph.adjList[i]){
                System.out.print(pCrawl+" ");
            }
            System.out.println("");
        }
    }

Which will output the following:

1 2
2
0 3
3

If you want to rotate that, you simply need to change the adding Parameters :)

Upvotes: 0

Related Questions