Using the same graph that was used in dfs not getting the same answer. In fact some of the nodes are missing.
The code -
template
class Graph {
unordered_map<T, list> l;
public:
void addEdge(T x, T y) {
l[x].push_back(y);
}
void topological_sort() {
unordered_map<T, int> indegree;
// initialize indegree of nodes with 0
for(auto p : l) indegree[p.first] = 0;
for(auto p : l) {
T node = p.first;
for (auto nbr : p.second) indegree[nbr]++;
}
// BFS
queue<T> q;
// 1. Find nodes with 0 indegree
for(auto p : l) {
if (indegree[p.first] == 0) q.push(p.first);
}
// Start removing nodes from the queue
while(!q.empty()) {
T node = q.front();
cout << node << " ";
q.pop();
// Iterarte over neighbours
for(auto nbr : l[node]) {
indegree[nbr]--;
if (indegree[nbr]) q.push(nbr);
}
}
}
};
int main() {
Graph g;
g.addEdge(“Python”, “PyTorch”);
g.addEdge(“Python”,“MLBasics”);
g.addEdge(“Python” , “DataPreprocessing”);
g.addEdge(“DataPreprocessing”, “MLBasics”);
g.addEdge(“PyTorch”, “DeepLearning”);
g.addEdge(“DeepLearning”, “FaceRecognition”);
g.addEdge(“MLBasics”, “DeepLearning”);
g.addEdge(“Dataset”, “FaceRecognition”);
g.topological_sort();
return 0;
}