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

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...
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...
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.
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.
Build a simple list implementation that uses arrays to store the values. Create a class SimpleArrayList...
Build a simple list implementation that uses arrays to store the values. Create a class SimpleArrayList with a public constructor that initializes the list using a passed array of Object references. Assert that the passed array is not null. Next, implement: 1)Object get(int), which takes an int index and returns the Object at that index 2)void set(int, Object), which takes an int index and an object reference and sets that value at the index to the passed reference Both your...
Write a Python program that uses function(s) for writing to and reading from a file: a....
Write a Python program that uses function(s) for writing to and reading from a file: a. Random Number File Writer Function Write a function that writes a series of random numbers to a file called "random.txt". Each random number should be in the range of 1 through 500. The function should take an argument that tells it how many random numbers to write to the file. b. Random Number File Reader Function Write another function that reads the random numbers...
Array-Based Linked List Implementation: JAVA Decide how to write the methods with items being stored in...
Array-Based Linked List Implementation: JAVA Decide how to write the methods with items being stored in an array. NOT in linked List. Implement an array-based Linked List in your language. Use double as the item. You need to create a driver includes several items and inserts them in order in a list. Identify the necessary methods in a List Linked implementation. Look at previous Data Structures (stack or queue) and be sure to include all necessary methods. DO NOT USE...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT