nikunjsoni

207

May 30th, 2021
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.86 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     bool canFinish(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.         queue<int> q;
  14.         for(int i=0; i<n; i++)
  15.             if(!inDegree[i])
  16.                 q.push(i);
  17.        
  18.         while(!q.empty()){
  19.             int node = q.front(); q.pop();
  20.             for(auto child: graph[node])
  21.                 if(--inDegree[child] == 0)
  22.                     q.push(child);
  23.         }
  24.        
  25.         // Check for cycle.
  26.         for(int i=0; i<n; i++)
  27.             if(inDegree[i])
  28.                 return false;
  29.         return true;
  30.     }
  31. };
Advertisement
Add Comment
Please, Sign In to add comment