207.课程表
207.课程表
题解
题目:给你一个课表,<x,y>,需要先修x,才能修y,问是否能上完所有课
思路:典型的拓扑排序的问题,bfs即可
代码
func canFinish(numCourses int, prerequisites [][]int) bool { indeg := make([]int, numCourses) mp := make(map[int][]int) queue := make([]int, 0) for _, v := range prerequisites { indeg[v[1]]++ mp[v[0]] = append(mp[v[0]], v[1]) } for i, v := range indeg { if v == 0 { queue = append(queue, i) } } for len(queue) != 0 { top := queue[0] queue = queue[1:] v := mp[top] delete(mp, top) for _, vv := range v { indeg[vv]-- if indeg[vv] == 0 { queue = append(queue, vv) } } } cnt := 0 for _, v := range indeg { cnt += v } return cnt == 0 }