-
Notifications
You must be signed in to change notification settings - Fork 211
Expand file tree
/
Copy pathGraph.java
More file actions
executable file
·93 lines (85 loc) · 1.68 KB
/
Graph.java
File metadata and controls
executable file
·93 lines (85 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package ca.mcmaster.chapter.four.graph;
import java.awt.DisplayMode;
public interface Graph {
/**
* @Description: Get the vertex number.
* @return
*/
public int V();
/**
* @Description: Get the edge number.
* @return
*/
public int E();
/**
* @Description: Create an edge between w and v.
* @param v
* @param w
*/
public void addEdge(int v, int w);
/**
* @Description: Get all vertex adjacent to v.
* @param v
* @return
*/
public Iterable<Integer> adj(int v);
/**
* @Description: Return degree of given vertex.
* @param G
* @param V
* @return
*/
static Integer degree(Graph G, int V){
Integer degree = new Integer(0);
for(int w : G.adj(V)) degree++;
return degree;
}
/**
* @Description: Find the largest degree in the graph
* @param G
* @param V
* @return
*/
static int maxDegree(Graph G, int V){
int max = 0;
for(int w : G.adj(V) )
if(w > max)
max = w;
return max;
}
/**
* @Description: Calculate the average degree for all vertex.
* @param G
* @return
*/
static double avgDegree(Graph G){
return 2 * G.E() / G.V();
}
/**
* @Description: Get the number of selt loop.
* @param G
* @param V
* @return
*/
static int numOfSelfLoop(Graph G, int V){
int num = 0;
int vNum = G.V();
for(int v = 0; v < vNum; v++ )
for(int w : G.adj(v))
if(w == v)
num ++;
return num/2; //w,v and v,w will both be counted.
}
/**
* @Description: Print a graph.
*/
default void display(){
int vertexNum = this.V();
for(int v = 0; v < vertexNum; v++){
StringBuilder sb = new StringBuilder(v + " -> ");
for(int w : adj(v))
sb.append(w + "");
System.out.println(sb.toString());
}
}
}