-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.java
More file actions
53 lines (46 loc) · 1.38 KB
/
Copy pathGraph.java
File metadata and controls
53 lines (46 loc) · 1.38 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
package graphs;
public class Graph {
private int v;
public Graph(int v) {
this.v = v;
}
public Vertex createVertex(String label) {
return new Vertex(label);
}
public void printGraphDFS(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]);
printGraphDFS(s);
}
}
}
// Recursive Approach - not ideal for large graphs
public void printGraphBFS(Queue queue) {
if (queue.isEmpty()) {
return;
}
Vertex current = queue.dequeue();
if (current == null || current.isVisited) {
printGraphBFS(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);
}
}
}
printGraphBFS(queue);
}
}