-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBfsDfsForDirectedGraph.java
More file actions
81 lines (69 loc) · 2.42 KB
/
Copy pathBfsDfsForDirectedGraph.java
File metadata and controls
81 lines (69 loc) · 2.42 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
package graphs;
public class BfsDfsForDirectedGraph {
public static void main(String[] args) {
Graph graph = new Graph(5);
Vertex a, b, c, d, e;
a = graph.createVertex("A");
b = graph.createVertex("B");
c = graph.createVertex("C");
d = graph.createVertex("D");
e = graph.createVertex("E");
// Directed Graph
a.addNeighbours(new Vertex[]{b, d});
b.addNeighbours(new Vertex[]{c});
c.addNeighbours(new Vertex[]{});
d.addNeighbours(new Vertex[]{e});
e.addNeighbours(new Vertex[]{});
Queue queue = new Queue();
queue.enqueue(a);
System.out.print("\nBreadth First Traversal: ");
bfsDirectedGraph(queue);
resetVisitedFlags(a, b, c, d, e);
LinkedListStack ls = new LinkedListStack();
ls.push(a);
System.out.print("\nDepth First Traversal: ");
dfsDirectedGraph(ls);
}
// Task : Perform Breadth first traversal and depth first traversal for Directed graph.
private static void bfsDirectedGraph(Queue queue) {
if (queue.isEmpty()) {
return;
}
Vertex current = queue.dequeue();
if (current == null || current.isVisited) {
bfsDirectedGraph(queue);
return;
}
current.isVisited = true;
System.out.print(current.label + " ");
if (current.neighbour != null) {
for (Vertex neighbour: current.neighbour) {
if (neighbour != null && !neighbour.isVisited) {
queue.enqueue(neighbour);
}
}
}
bfsDirectedGraph(queue);
}
private static void dfsDirectedGraph(LinkedListStack s) {
s.peek().isVisited = true;
Vertex current = s.peek();
if (current == null) {
return;
}
System.out.print(current.label + " ");
s.pop();
for (int i = 0; i < current.neighbour.length; i++) {
if (!current.neighbour[i].isVisited) {
s.push(current.neighbour[i]);
dfsDirectedGraph(s);
}
}
}
// helper method to reset visited flag for each node/vertex
private static void resetVisitedFlags(Vertex... vertices) {
for (Vertex vertex: vertices) {
vertex.isVisited = false;
}
}
}