Question

In: Computer Science

Java Implementation It uses adjacency list representation, and already has the loadAdjList() function implemented for reading...

Java Implementation

It uses adjacency list representation, and already has the loadAdjList() function implemented for reading adjacency lists from standard input (make sure you understand the input format and how loadAdjList() works). You need to complete the function printAdjMatrix().

import java.util.LinkedList;
import java.util.Scanner;
import java.util.Iterator;
class Graph {
private int totalVertex;
private LinkedList<LinkedList<Integer>> adjList;
//adjacency list of edges
public Graph() { totalVertex = 0; }
public void loadAdjList() {
Scanner in = new Scanner(System.in);
totalVertex = in.nextInt();
adjList = new LinkedList<LinkedList<Integer>>();
for(int i = 0; i < totalVertex; i ++) {
LinkedList<Integer> tmp = new LinkedList<Integer>();
int idx1 = in.nextInt() - 1;
int degree = in.nextInt();
//System.out.println("mark idx1 = " + idx1 + " degree = " + degree);
for(int j = 0; j < degree; j ++) {
int idx2 = in.nextInt() - 1;
tmp.add(idx2);
}
adjList.add(tmp);
}
in.close();
}
public void printAdjMatrix() {
Integer[][] adjMatrix = new Integer[totalVertex][totalVertex];
//complete the following
}
}
//change class name GraphRepresentation to Main() for submission to AIZU
public class GraphRepresentation {
public static void main(String argv[]) {
Graph g = new Graph();
g.loadAdjList();
g.printAdjMatrix();
}
}

Solutions

Expert Solution

first of all lets in brief discuss about adjacency list and adjacency matrix representation of a graph..

adjacency list representation is : an array/ linked list of linked lists which stores for every vertex in the graph in the graph we store it's neighbouring vertices ( current vertex and neighbouring vertex are connected by an edge)

that is each vertex gets its own linked list in which all the neighbouring vertices are stored..

for a graph with n vertices we will have n separate linked lists which will be joined by a single linked list / single array

adjacency matrix representation : if there are n vertices then we will have a n * n matrix adjMatrix in which if there is an edge from i->j then adjMatrix[i][j] = 1 else if there is no edge from i to j then adjMatrix[i][j] = 0]

in case of undirected graph : edges are bidirectional i.e., if i is a neighbour to j then j is also a neighbour of i, it was not mentioned here so we will be taking an directed graph i.e., if i is a neighbour to j then it does not imply j is also a neighbour of i.

a sample illustartion :

suppose if our graph is like this then the corresponding adjacency list and adjacency matrix will be like this :

after getting an idea about them we can solve this question : what we have to do :

1understanding the working of loadAdjList function given , which is used to create the adjacency list of the graph

2 we should complete a function printAdjMatrix , which given an adjacency list prints the adjacency matrix of the adjacency list

1. here's what the function is doing .. initially we have no graph,

that's why we will initialise an empty linkedList of (linkedList of (nodes) )

* ask the user enter no of vertices in our graph -  totalVertex

*for each vertex i ask the no of neighbouring vertices of this vertex i - degree

* now initialise an empty LinkedList of integers - tmp

* ask the user to enter neighbouring vertices of this graph one by one they should be a total of degree number of vertices

* add each neighbouring vertex to our current vertex LinkedList tmp

* after adding each vertex into tmp LinkedList we will have our current vertex i's corresponding linkedList of nodes

* now we should add this tmp LinkedList(nodes) to our adjList (LinkedList)

* after doing this for every vertex i>=0 and i <totalVertex we will have our final adjacency list in adjList.

i have included some comments and print statements to make the code and input more clear :

public void loadAdjList(){

Scanner in = new Scanner(System.in);

System.out.println("enter total no of vertices in graph\n");

totalVertex = in.nextInt();

adjList = new LinkedList<LinkedList<Integer>>(); //initialising adjList data member

                                                // linked list of totalVertex no of linked lists

                                                // each linked list is for each vertex

for(int i = 0; i < totalVertex; i ++) {

LinkedList<Integer> tmp = new LinkedList<Integer>(); // for each vertex a linked list

System.out.println("enter the to node number : "+ (i+1));

int idx1 = in.nextInt() - 1;

// if we are treating it as a zeros based naming like first node if 0

System.out.println("enter no nodes connected to node : "+ (i+1));

int degree = in.nextInt();   // no of connections/outward- edges this node has

System.out.println("mark idx1 = " + idx1 + " degree = " + degree);

System.out.println("enter "+  degree +" no nodes connected to this node : ");

for(int j = 0; j < degree; j ++) { // for each connection/edge

int idx2 = in.nextInt() - 1; // we are getting each node other side of the connection

tmp.add(idx2); // we are adding each node connected to our current node i to the linked list tmp

}

adjList.add(tmp); // as tmp is contains our linked list of vertices connected to our current node i

                // we will add it to our adjacency list..

                // here we are adding the linked list tmp to adjacency list adjList

}

in.close(); //closing the input scanner

}

input format :

no_of vertices in the graph n

for each vertex it will ask the number of its vertex ( the user views the starting the vertex as 1 ans in the code it will be 0)

degree of each vertex d

d no of vertices connected to current vertex ..

sample input for the graph in above explanation after adding useful comments:

enter total no of vertices in graph
6
enter the node number : 1
1
enter no nodes connected to node : 1
2
mark idx1 = 0 degree = 2
enter 2 no nodes connected to this node :
2 3
enter the node number : 2
2
enter no nodes connected to node : 2
2
mark idx1 = 1 degree = 2
enter 2 no nodes connected to this node :
3 4
enter the node number : 3
3
enter no nodes connected to node : 3
1
mark idx1 = 2 degree = 1
enter 1 no nodes connected to this node :
5
enter the node number : 4
4
enter no nodes connected to node : 4
2
mark idx1 = 3 degree = 2
enter 2 no nodes connected to this node :
2 5
enter the node number : 5
5
enter no nodes connected to node : 5
3
mark idx1 = 4 degree = 3
enter 3 no nodes connected to this node :
6 4 3
enter the node number : 6
6
enter no nodes connected to node : 6
1
mark idx1 = 5 degree = 1
enter 1 no nodes connected to this node :
3

now printing adjacency matrix..

*first we will initialise an matrix adjMatrix[totalVertex][totalVertex] and keep all 0<= i , j < totalVertex ; adjMatrix[i][j] = 0

then for each linked list of nodes in our adjList - tmp

for each node in tmp - neighbour

adjMatrix[ current vertex] [neighbour] = 1

then later print the whole matrix.

public void printAdjMatrix() {

Integer[][] adjMatrix = new Integer[totalVertex][totalVertex];

for(int i=0;i<totalVertex;i++)

    for(int j=0;j<totalVertex;j++)

        adjMatrix[i][j] = 0; // initialise all adjMatrix[i][j] = 0

LinkedList<Integer> tmp ; // linked list of nodes

for (int i=0;i<totalVertex;i++){

    tmp = adjList.get(i); // linked list of each node for i =0 to i<totalVertex

    for(int node :tmp ){

        adjMatrix[i][node] = 1;

    }

}

System.out.println("the adjacency matrix for the graph is ");

for(int i=0;i<totalVertex;i++){

    for(int j=0;j<totalVertex;j++){

        System.out.print(adjMatrix[i][j]+ " "); // printing the whole matrix

    }

    System.out.print("\n");

}

}

output for sample graph given above :

the adjacency matrix for the graph is

0 1 1 0 0 0
0 0 1 1 0 0
0 0 0 0 1 0
0 1 0 0 1 0
0 0 1 1 0 1
0 0 1 0 0 0

please provide your valuable feedback.


Related Solutions

Answer True or False 1. For graph representation, adjacency Matrix is more efficiency than adjacency list...
Answer True or False 1. For graph representation, adjacency Matrix is more efficiency than adjacency list in term of searching for edge. 2. Topological sort runs in O(|V| + |E|) where |V| is the number of vertices, and |E| is the number of edges in the input graph. 3. If vertex u can reach vertex v, and vertex v can reach vertex u, then vertices u and v are in the same Strongly-connected component (SCC). 4. The Bellman-Ford algorithm will...
Java The List ADT has an interface and a linked list implementation whose source code is...
Java The List ADT has an interface and a linked list implementation whose source code is given at the bottom of this programming lab description. You are to modify the List ADT's source code by adding the method corresponding to the following UML: +hasRepeats() : boolean hasRepeats() returns true if the list has a value that occurs more than once in the list hasRepeats() returns false if no value in the list occurs more than once in the list For...
Java The List ADT has an interface and a linked list implementation whose source code is...
Java The List ADT has an interface and a linked list implementation whose source code is given at the bottom of this programming lab description. You are to modify the List ADT's source code by adding the method corresponding to the following UML: +hasRepeats() : boolean hasRepeats() returns true if the list has a value that occurs more than once in the list hasRepeats() returns false if no value in the list occurs more than once in the list For...
Suppose the interface and the class of stack already implemented, Write application program to ( java)...
Suppose the interface and the class of stack already implemented, Write application program to ( java) 1- insert 100 numbers to the stack                         2- Print the even numbers 3- Print the summation of the odd numbers
(Javascript) /* * USER HAS ALREADY BEEN IMPLEMENTED FOR YOU: * User has the following properties:...
(Javascript) /* * USER HAS ALREADY BEEN IMPLEMENTED FOR YOU: * User has the following properties: * name: string * birthday: Date * * User has the following method: * getDayBorn: Returns the day of the week that the user was born * example: Wednesday */ function User(name, birthday) { this.name = name; this.birthday = birthday; this.getDayBorn = function() { var days = [`Sunday`,`Monday`,`Tuesday`, `Wednesday`,`Thursday`,`Friday`,`Saturday`]; return days[this.birthday.getDay()]; } } /* * YOUR TASK IS TO IMPLEMENT CHIRP: * Chirp has...
******IN JAVA******** I need the following interface implemented accordingly. It is a linked list. The interface...
******IN JAVA******** I need the following interface implemented accordingly. It is a linked list. The interface can be found below: List.java public interface List<T> extends Iterable<T> { /** * Insert an element at a specified location. * @param index * @param obj * @throws IndexOutOfBoundsException */ public void add(int index, T obj); /** * Append an object to the end of the list. * @param obj */ public boolean add(T obj); public void clear(); public boolean contains(T obj); /** *...
In C++ write an implementation of the ADT sorted list that uses a resizable array (vector...
In C++ write an implementation of the ADT sorted list that uses a resizable array (vector class of C++ STL) to represent the list items.
JAVA You will be given a grocery list, filed by a sequence of items that have already been purchased.
 Instructions You will be given a grocery list, filed by a sequence of items that have already been purchased. You are going to determine which items remain on the the list and output them so that you know what to buy. You will be give an integer n that describes how many items are on the original grocery list. Following that, you will be given an array of n grocery list items (strings) that you need to buy. After your grocery list...
Java the goal is to create a list class that uses an array to implement the...
Java the goal is to create a list class that uses an array to implement the interface below. I'm having trouble figuring out the remove(T element) and set(int index, T element). I haven't added any custom methods other than a simple expand method that doubles the size by 2. I would prefer it if you did not use any other custom methods. Please use Java Generics, Thank you. import java.util.*; /** * Interface for an Iterable, Indexed, Unsorted List ADT....
Question: Write an implementation of the ADT sorted list that uses a resizable array (vector class...
Question: Write an implementation of the ADT sorted list that uses a resizable array (vector class of C++ STL) to represent the list items. Anytime the list becomes full, double the size of the array.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT