There is a total of n courses you have to take, labeled from 0 to N-1.
Some courses May has prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a Pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, are it possible for your to finish all courses?
For example:
2, [[1,0]]
There is a total of 2 courses to take. To take course 1 should has finished course 0. So it is possible.
2, [[1,0],[0,1]]
There is a total of 2 courses to take. To take course 1 should has finished course 0, and to take course 0 you should also has finished course 1. So it is impossible.
Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more on how a graph is represented.
Ask if there is a ring in the graph .
Topology sorting
maintains all nodes with a queue of 0, one at a time, and a node V to see all nodes from v u; The
converts the read-in to u minus one, and if you are at this point 0, you join the queue.
When the queue is empty, check the degree of all the nodes, if all nodes in the degree is 0, there is a topological sort--there is no ring in the graph.
Class Solution {Public:bool canfinish (int numcourses, vector<pair<int, int>>& prerequisites) {
Vector<int> Indgree (numcourses,0);
Map<int, vector<int> >adjNode;
int len = Prerequisites.size ();
for (int i = 0; i < len; i++) {pair<int, int> p = prerequisites[i]; if (Find (Adjnode[p.second].begin (), Adjnode[p.second].end (), p.first) = = Adjnode[p.second].end ()) {Adjnode
[P.second].push_back (P.first);
indgree[p.first]++;
}} queue<int> Q;
for (int i=0; i < numcourses; i++) {if (indgree[i] = = 0) Q.push (i); } while (!
Q.empty ()) {int front = Q.front ();
Q.pop ();
vector<int> adj = Adjnode[front];
for (int i:adj) {indgree[i]--;
if (indgree[i] = = 0) {Q.push (i); }}} for (int i:indgree) {if (i) return false;
} return true;
}
};