Graphs
Last updated
public class Graph{
// Initialize the graph with v vertices
Graph(int v);
// Add an edge between vertex v and vertex w
void addEdge(int v , int w);
// Vertices adjacent to v
Iteratable<Integer> adj(int v);
// Number of Vertices
int V();
// Number of Edges
int E();
}public static int degree(Graph G, int v){
int degree = 0;
for(int w : G.adj(v) ){
degree++;
}
return degree;
}public static int maxDegree(Graph G){
int max = 0;
for( int v=0; v < G.V(); v++ ){
max = Math.max(degree(G, v), max);
}
return max;
}public static double averageDegree(Graph G){
return 2.0 * G.E() / G.V();
}public static int countSelfLoops(Graph G){
int count = 0;
for(int v=0;v<G.V(); v++){
for(int w: G.adj(v)){
if(v == w) {
count++;
}
}
}
return count/2; // Each edge counted twice
}