码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode207

时间:2018-10-06 12:01:29      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:拓扑排序   push   排序   vector   can   return   sizeof   --   color   

拓扑排序问题。

class Solution {
public:
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        int Hash[10010];//每个节点的入度
        vector<vector<int>> v(numCourses);//用于存储每个节点相邻的边
        stack<int> s;//存放入度为0的节点
    memset(Hash, 0, sizeof(Hash));
    for(int i =0 ; i < prerequisites.size();i++){
        pair<int, int>p = prerequisites[i];
        int x = p.first;
        int y = p.second;
        cout<<"x = "<<x <<"y = "<<y<<endl;
        v[x].push_back(y);
        ++Hash[y];
    }
    for(int i = 0; i < numCourses; i++){
        if(Hash[i] == 0){
            s.push(i);
        }
    }
    while (!s.empty()) {
        int cur = s.top();//找到入度为0的点
        s.pop();
        for(int i = 0; i < prerequisites.size(); i++){
            pair<int, int>p = prerequisites[i];
            int x = p.first;
            int y = p.second;
            if(cur == x){
                for(int j = 0; j < v[cur].size(); j++){
                    --Hash[v[cur][j]];//删除以该点为起点的所有有向边
                    if(Hash[v[cur][j]] == 0)
                        s.push(v[cur][j]);
                }
                break;
            }
        }
    }
    for(int i = 0; i < numCourses; i++){
        if(Hash[i] != 0)
            return false;
    }
    return true;
    }
};

 

leetcode207

标签:拓扑排序   push   排序   vector   can   return   sizeof   --   color   

原文地址:https://www.cnblogs.com/asenyang/p/9746691.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!