算法設計與應用基礎: 第五週(1)

207. Course Schedule

  • Total Accepted: 73778
  • Total Submissions: 237565
  • Difficulty: Medium
  • Contributors: Admin

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have 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, is it possible for you to finish all courses?


解題思路:分析題意就是讓你求一個圖中是否存在迴路,最直接的辦法就是利用拓撲排序來判斷。結合在課上所講的利用dfs來進行判斷,最重要的就是一直維護每個頂點的入度序列,每次將一個入度數爲0的頂點彈出,就更新一次這個度序列

代碼如下:

bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        int degree[numCourses];
        vector<vector<int> >g_list;
        for(int i=0;i<numCourses;i++)
        {
            vector<int> temp;
            g_list.push_back(temp);
        }
        //memset(graph,0,sizeof(graph));
        memset(degree,0,sizeof(numCourses));
        for(int i=0;i<prerequisites.size();i++)
        {
            if(prerequisites[i].first==prerequisites[i].second)
                return false;
            else
            {
                degree[prerequisites[i].first]++;
                g_list[prerequisites[i].second].push_back(prerequisites[i].first);
            }
        }
        queue<int> sort;
        //int first=-1;
        for(int i=0;i<numCourses;i++)
        {
            if(degree[i]==0)
            {
                sort.push(i);
            }
        }
        
            int count=sort.size();
            //sort.push(first);
            //cout<<first<<endl;
            while(!sort.empty())
            {
                int temp=sort.front();
                sort.pop();
                //count++;
                for(int i=0;i<g_list[temp].size();i++)
                {
                    degree[g_list[temp][i]]--;
                    if(degree[g_list[temp][i]]==0)
                    {
                        count++;
                        sort.push(g_list[temp][i]);
                    }
                }
            }
            //cout<<count<<endl;
            return count==numCourses;
        
        
    }

總結:拓撲排序是深度優先的很好使用,針對不同的情況可以使用圖的鄰接表或者鄰接矩陣表示,使得複雜度降低


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章