-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBFS.java
150 lines (124 loc) · 2.32 KB
/
BFS.java
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
class Queue {
private int max,rear,front;
private int[] a;
public Queue(int max) {
this.max = max;
a = new int[max];
rear = front = -1;
}
public void insert(int val) {
if(isFull()) {
System.out.println("overflow");
} else {
if(isEmpty()) {
front = rear = 0;
a[rear] = val;
} else {
rear++;
a[rear] = val;
}
}
}
public int front() {
return a[front];
}
public boolean isFull() {
if(rear == max -1) return true;
else return false;
}
public boolean isEmpty() {
if(rear == -1) return true;
else return false;
}
public int delete() {
if(isEmpty()) {
System.out.println("Underflow");
return -1;
} else {
int temp = a[front];
if(rear==front) {
rear = -1;
front = -1;
} else {
front++;
}
return temp;
}
}
}
class Vertex {
int label;
boolean isVisited;
Vertex(int label) {
this.label = label;
isVisited = false;
}
}
class Graph {
private Vertex V[];
private int vMax;
private int[][] adjMat;
public int nV;
private Queue q;
Graph(int vMax) {
this.vMax = vMax; // Maximum vertex can vbe added
nV = 1; // counter for the vertices we will work with 1
V = new Vertex[vMax + 1];
adjMat = new int[vMax + 1][vMax + 1];
q = new Queue(V.length);
}
public void addVertix(int label) {
V[nV] = new Vertex(label);
nV++;
}
public void addEdge(int s, int d) {
adjMat[s][d] = 1;
adjMat[d][s] = 1;
}
public int unVisitedAdjVet(int v) {
for(int i=1; i<nV; i++) {
if( adjMat[v][i] == 1 && !V[i].isVisited )
return i;
}
return -1;
}
public void bfs(int start) {
q.insert(start);
V[start].isVisited = true;
System.out.print(V[start].label + " ");
while(!q.isEmpty()) {
int vet = unVisitedAdjVet(q.front());
if(vet == -1) {
q.delete();
} else {
V[vet].isVisited = true;
System.out.print(V[vet].label + " ");
q.insert(vet);
}
}
}
}
class BFS {
public static void main(String[] args) {
Graph g = new Graph(5);
g.addVertix(1);
g.addVertix(2);
g.addVertix(3);
g.addVertix(4);
g.addVertix(5);
/*
2 - 3
/
1
\
4 - 5
*/
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(1, 4);
g.addEdge(4, 5);
g.bfs(1); // 1 2 4 3 5
//To get this output make sure to comment g.bfs(1)
g.bfs(2); // 2 1 3 4 5
}
}