-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.java
More file actions
132 lines (119 loc) · 2.87 KB
/
Graph.java
File metadata and controls
132 lines (119 loc) · 2.87 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package algorithm.graph;
import java.util.Iterator;
import java.util.LinkedList;
/**
* The type Graph.
*/
class Graph {
/**
* The Vertices.
*/
private int vertices;
/**
* The Adjacency list.
*/
private LinkedList<Integer> adjacencyList[];
/**
* Instantiates a new Graph.
*
* @param vertices the vertices
*/
public Graph(int vertices) {
this.vertices = vertices;
this.adjacencyList = new LinkedList[vertices];
for (int i = 0; i < vertices; ++i)
adjacencyList[i] = new LinkedList();
}
/**
* Add edge.
*
* @param source the source
* @param destination the destination
*/
// Function to add an edge into the graph
void addEdge(int source, int destination) {
adjacencyList[source].add(destination);
}
/**
* Gets vertices.
*
* @return the vertices
*/
public int getVertices() {
return this.vertices;
}
/**
* Get adj linked list [ ].
*
* @return the linked list [ ]
*/
public LinkedList<Integer>[] getAdj() {
return this.adjacencyList;
}
/**
* Print graph.
*/
public void printGraph() {
System.out.println("Adjacency List of Directed Graph");
for (int i = 0; i < this.vertices; i++) {
if (adjacencyList[i] != null) {
System.out.print("|" + i + "| => ");
for (int j = 0; j < adjacencyList[i].size(); j++) {
System.out.print("[" + adjacencyList[i].get(j) + "] -> ");
}
System.out.println("null");
} else {
System.out.println("|" + i + "| => " + "null");
}
}
}
/**
* Gets transpose.
*
* @return the transpose
*/
public Graph getTranspose(Graph graph) {
Graph g = new Graph(vertices);
for (int j = 0; j < vertices; j++) {
Iterator<Integer> i = adjacencyList[j].listIterator();
while (i.hasNext())
g.adjacencyList[i.next()].add(j);
}
return g;
}
/**
* Dfs traversal.
*
* @param v the v
* @param visited the visited
*/
public void dfsTraversal(int v, boolean visited[]) {
visited[v] = true;
int source = 0;
Iterator < Integer > i = adjacencyList[v].iterator();
Integer temp;
while (i.hasNext()) {
temp = i.next();
if (!visited[temp])
dfsTraversal(temp, visited);
}
}
}
/**
* The type Main.
*/
class Main {
/**
* Main.
*
* @param args the args
*/
public static void main(String args[]) {
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(2, 3);
g.addEdge(3, 0);
}
}