class Solution { public: bool canFinish(int numCourses, vector<vector<int>>& prerequisites) { //验证是否为DAG,每次验证指向的是否已经存在于当前图中 //建图 vector<int> indegree(numCourses,0);//入度 vector<vector<int>> graph(numCourses,vector(0,0));//邻接表 for(int i=0;i<prerequisites.size();i++){ indegree[prerequisites[i][1]]++;graph[prerequisites[i][0]].push_back(prerequisites[i][1]); } //显示图showgraph(graph,numCourses); //BFS queue<int> q; for(int i=0;i<numCourses;i++){ if(indegree[i]==0){ q.push(i); } } //将入度为0的点且未访问过的进入set,然后将其后继的入度全部减一,循环执行 int cnt=0; while(!q.empty()){ int front=q.front(); q.pop(); cnt++; for(int j=0;j<graph[front].size();j++){ int v=graph[front][j]; indegree[v]--; if(indegree[v]==0){ q.push(v); } } } return cnt==numCourses;//当有环时,总有一些点入度不能减到0,因此不能完全bfs遍历 } private: void showgraph(vector<vector<int>>& graph,int numCourses){ for(int i=0;i<numCourses;i++){ cout<<i<<": "; for(int j=0;j<graph[i].size();j++){ cout<<graph[i][j]<<","; } cout<<endl; } } };