Leetcode 207 curriculum

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/Mr_zhuo_/article/details/88550830

Thinking: topological sorting, determining acyclic

1. Establish a two-dimensional array record [] [], the recording point of each neighboring vertices

2.Hash [] for each vertex of the recording

3. = 0 point of the push

4. Each time the stack is a point x, the record [x] into the line of all points of -1-degree generating = 0 point is into the stack

5. Repeat 4 until the stack is empty

6. traversing the Hash [], if each element is 0, no ring, ring otherwise.

tip: because you want to own model, so the establishment of a two-dimensional array of recording more convenient (here was modified on the basis of adjacency matrix based on the record only up to the point, thus reducing the time consumption) is not recommended to write the adjacent table, the process of establishing more complicated .

Code:

class Solution {

public:
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        vector<vector<int>> record(numCourses);//存储每个节点相邻的边
        
        int Hash[10010];//记录入度
        memset(Hash,0,sizeof(Hash));
        
        //初始化二维数组,记录可达关系
        for(int i=0;i<prerequisites.size();i++)
        {
            pair<int,int> tmp=prerequisites[i];
            int x=tmp.first;
            int y=tmp.second;
            record[y].push_back(x);  
            Hash[x]++;
        }
        //0度入栈
        stack<int> s;
        for(int i=0;i<numCourses;i++)
        {
            if(Hash[i]==0) s.push(i);
        }
        
        //图的拓扑排序
        while(!s.empty())
        {
            int tmp=s.top();
            s.pop();
            for(int i=0;i<record[tmp].size();i++)
            {
                int k=record[tmp][i];
                Hash[k]--;
                if(Hash[k]==0) s.push(k);
            }
        }
        for(int i=0;i<numCourses;i++)
        {
            if(Hash[i]!=0) return false;
        }
        return true;
    }
};

 

Guess you like

Origin blog.csdn.net/Mr_zhuo_/article/details/88550830