forked from anku580/Java-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFSgraph.java
More file actions
61 lines (50 loc) · 1.22 KB
/
BFSgraph.java
File metadata and controls
61 lines (50 loc) · 1.22 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
import java.util.LinkedList;
import java.util.Stack;
import sun.misc.Queue;
public class BFSgraph {
private boolean[] marked;
private int[] edgeTo;
private int s;
public Queue<Integer>que = new Queue<>();
DFSgraph(Graph g, int s) {
marked = new boolean[g.V()];
edgeTo = new int[g.V()];
this.s = s;
bfs(g, s);
}
public void bfs(Graph g, int v) {
que.push(v);
while(que.isEmpty())
{
int vert = que.pop();
marked[vert] = true;
for(int w : g.adj(vert))
{
if(!marked[w]) {
que.push(w);
edgeTo[w] = v;
}
}
}
}
public void printEle(int d) {
int i = d;
while(i != s) {
System.out.println(i);
i = edgeTo[i];
}
}
public static void main(String args[]) {
Graph g = new Graph(7);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(0, 5);
g.addEdge(0, 6);
g.addEdge(5, 3);
g.addEdge(5, 4);
g.addEdge(3, 4);
g.addEdge(4, 6);
BFSgraph d = new BFSgraph(g, 0);
d.printEle(3);
}
}