题目:207. 课程表
思路:拓扑排序经典题型。
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
//邻接表:记录先后关系
vector<vector<int>> g(numCourses,vector<int>());
//哈希表:存储每个节点的入度值
vector<int> sta(numCourses,0);
//遍历数组prerequisites,预处理出邻接表、哈希表
for(auto tmp:prerequisites){
int x=tmp[0],y=tmp[1];
//入度+1
sta[x]++;
//记录出度
g[y].push_back(x);
}
//队列,存储可以学习的课程,即入度为0
queue<int> qu;
//找出最开始入度为0的课程
for(int i=0;i<numCourses;i++){
if(sta[i]==0) qu.push(i);
}
//记录可以学习的课程数
int res=0;
//广度优先搜索bfs
while(qu.size()){
res++;
int tmp=qu.front();
qu.pop();
//减少入度
for(auto x:g[tmp]){
sta[x]--;
if(sta[x]==0) qu.push(x);
}
}
return res==numCourses;
}
};
JAVA版本:
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
邻接表:记录先后关系
List<Integer>[] g =new List[numCourses];
Arrays.setAll(g,i->new ArrayList<Integer>());
//哈希表:存储每个节点的入度值
int[] sta = new int[numCourses];
//遍历数组prerequisites,预处理出邻接表、哈希表
for(var x:prerequisites){
sta[x[0]]++;
g[x[1]].add(x[0]);
}
//队列,存储可以学习的课程,即入度为0
Queue<Integer> qu=new LinkedList<Integer>();
//找出最开始入度为0的课程
for(int i=0;i<numCourses;i++){
if(sta[i]==0) qu.offer(i);
}
//记录可以学习的课程数
int res=0;
//广度优先搜索bfs
while(!qu.isEmpty()){
res++;
int tmp=qu.poll();
//减少入度
for(var x:g[tmp]){
sta[x]--;
if(sta[x]==0) qu.offer(x);
}
}
return res==numCourses;
}
}