Sunday, August 4, 2013

Adjacency list represention of graph in Java

Here is the program for adjacency list representation of graphs using java. If you are new to Graphs please read about graphs here before reading the rest of this post.

Code:
package com.vaani.algo.graph.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class GraphUsingAdjList {


 class Node {
     int node;
     List<Integer> adjList;
     boolean visited;
 }


     void insertVertices() throws IOException
     {
          BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
         System.out.println("Enter number of nodes in a graph: ");
         int n=(Integer.parseInt(br.readLine()));
         Node g[]=new Node[n];
         for (int i = 0; i < n; i++) {
             g[i]=new Node();
             g[i].node=i+1;
             g[i].visited=false;
             while(true)
             {
                 System.out.println("Enter zero to stop");
                 System.out.println("Enter adjacent nodes to node "+(i+1)+" :");
                  int adjVertex=Integer.parseInt((br.readLine()));
                  if(adjVertex==0)
                      break;
                  else
                  {

                         
                         if(g[i].adjList==null)
                         {
                          List<integer> l=new ArrayList<nteger>();
                          l.add(adjVertex);
                             g[i].adjList=l;
                         }
                         else
                         {
                             List<integer> p= (List<Integer>)g[i].adjList;
                             p.add(adjVertex);
                         }
                  }
             }
         }
         System.out.println("Adjacency matrix representation");
         for (int i = 0; i < n; i++) {
             System.out.print(g[i].node+" --> ");
             List<Integer> l=g[i].adjList;
             
             if(l!=null)
             for(int node : l)
             {
               System.out.print(node+" --> ");
             }

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

     public static void main(String[] args) throws IOException {
              new GraphUsingAdjList().insertVertices();
     }

 
}

Let me know if you face any issues. Thanks

0 comments:

Post a Comment