-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKhans_Algorithm-Toplogical-Sorting--BFS.cpp
More file actions
72 lines (58 loc) · 1.29 KB
/
Copy pathKhans_Algorithm-Toplogical-Sorting--BFS.cpp
File metadata and controls
72 lines (58 loc) · 1.29 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
#include <bits/stdc++.h>
using namespace std;
int graph[10][10];
void createGraph(int i, int j, vector<int> &indegree)
{
graph[i][j] = 1;
indegree[j]++;
}
void KhansAlgorithm(int v, vector<int> &indegree)
{
vector<int> answer;
queue<int> q;
for (int i = 1; i <= v; i++)
{
if (indegree[i] == 0)
q.push(i);
}
while (!q.empty())
{
int current = q.front();
answer.push_back(current);
q.pop();
for (int i = 1; i <= v; i++)
{
if(graph[current][i] != 0)
{
indegree[i]--;
if(indegree[i] == 0)
q.push(i);
}
}
}
for (int i = 0; i < v; i++)
cout << answer[i] << " ";
}
int main()
{
int V, edge, i, j;
cout << "\nEnter the number of vertex : ";
cin >> V;
vector<int> indegree(V + 1, 0);
for (i = 1; i <= V; i++)
for (j = 1; j <= V; j++)
graph[i][j] = 0;
for (i = 1; i <= V; i++)
{
while (1)
{
cout << "Enter the edges from " << i << " or press -1 : ";
cin >> edge;
if (edge == -1)
break;
createGraph(i, edge, indegree);
}
}
KhansAlgorithm(V, indegree);
return 0;
}