Advertisement
nikunjsoni

210

May 30th, 2021
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.89 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> findOrder(int n, vector<vector<int>>& prerequisites) {
  4.         // Create adj list and indegree vector.
  5.         vector<vector<int>> graph(n);
  6.         vector<int> inDegree(n, 0);
  7.         for(auto pre: prerequisites){
  8.             graph[pre[1]].push_back(pre[0]);
  9.             inDegree[pre[0]]++;
  10.         }
  11.        
  12.         // Topo sort using bfs.
  13.         vector<int> order;
  14.         queue<int> q;
  15.         for(int i=0; i<n; i++)
  16.             if(!inDegree[i])
  17.                 q.push(i);
  18.        
  19.         while(!q.empty()){
  20.             int node = q.front(); q.pop();
  21.             order.push_back(node);
  22.             for(auto child: graph[node])
  23.                 if(--inDegree[child] == 0)
  24.                     q.push(child);
  25.         }
  26.        
  27.         // Check for cycle.
  28.         if(order.size() != n) return vector<int>{};
  29.         return order;
  30.     }
  31. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement