Please write the method in java. Thank you so much. WORK OUT THE SOLUTION TO THI
ID: 3818449 • Letter: P
Question
Please write the method in java. Thank you so much.
WORK OUT THE SOLUTION TO THIS PROBLEM AND TURN IT IN AT RECITATION You are given a directed graph: class Neighbor { public int vertex; public Neighbor next; ... } class Vertex { String name; Neighbor neighbors; // adjacency linked lists for all vertices } public class Graph { Vertex [] vertices; // returns an array of indegrees of the vertices i.e. return [i] is the // number of edges that are directed IN TO vertex i public int[ ] indegrees () { // FILL IN THIS METHOD ... } ... } Assuming that the graph has already been read in, complete the indegrees method.Explanation / Answer
/**
*
* @author Sam
*/
class Neighbor {
public int vertex;
public Neighbor next;
}
class Vertex {
String name;
Neighbor neighbors; // adjacency linked lists for all vertices
}
public class Graph {
Vertex[] vertices;
// returns an array of indegrees of the vertices, i.e. return!i] is the
// number of edges that are directed IN TO vertex i
public int[] indegrees() {
/*size of indegree array is equal to the length of vertices*/
int[] inDeg = new int[vertices.length];
/* To find the indegree we check the neighbour of all the vertices
* and increase the count of the neighboring vertx
* e.g. suppose vertex 2 has neighboring vertices 3, 4, 5,
* we shall increase the indegree count of vertex 3, 4 and 5 by 1
*/
for (Vertex v: vertices) {
Neighbor temp = v.neighbors;
while (temp!=null) {
inDeg[temp.vertex]++;
temp = temp.next;
}
}
return inDeg;
}
}
This is the simplest possible solution possible. You can find the implementation logic as multiline comment in the code. I hope that you like the code. Incase you are having difficulty understanding the code, you can comment below.