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

LeetCode Course Schedule II

时间:2015-05-14 16:40:02      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:c   malloc   拓扑排序   

题目
技术分享

思路
还是拓扑排序的思路。需要注意的是,这题的量变大了,会有2000门或以上的课,因此用malloc动态分配数组。
其实C真的挺好玩。

代码

int * findOrder(int numCourses, int ** prerequisites, int prerequisitesRowSize, int prerequisitesColSize, int * returnSize) {
    int * Indegrees;
    int * Outdegrees;
    int ** IsConnect;
    Indegrees = (int*)malloc(sizeof(int) * numCourses);
    Outdegrees = (int*)malloc(sizeof(int) * numCourses);
    IsConnect = (int**)malloc(sizeof(int*) * numCourses);
    for (int i = 0; i < numCourses; i++) Indegrees[i] = Outdegrees[i] = 0;
    for (int i = 0; i < prerequisitesRowSize; i++) {
        Indegrees[prerequisites[i][0]]++;
        Outdegrees[prerequisites[i][1]]++;
    }
    for (int i = 0; i < numCourses; i++) {
        IsConnect[i] = (int*)malloc(sizeof(int) * (Outdegrees[i] + 1));
        IsConnect[i][0] = 0;
    }
    for (int i = 0; i < prerequisitesRowSize; i++) {
        IsConnect[prerequisites[i][1]][++IsConnect[prerequisites[i][1]][0]] = prerequisites[i][0];
    }

    int * Q = (int*)malloc(sizeof(int) * numCourses);
    int head = 0, tail = 0, Ans = 0;
    for (int i = 0; i < numCourses; i++) {
        if (Indegrees[i] == 0) {
            Q[tail++] = i;
            Ans++;
        }
    }
    int * Order = (int*)malloc(sizeof(int) * numCourses);
    int k = 0;
    while (head < tail) {
        for (int i = 1; i <= IsConnect[Q[head]][0]; i++) {
            Indegrees[IsConnect[Q[head]][i]]--;
            if (Indegrees[IsConnect[Q[head]][i]] == 0) {
                Q[tail++] = IsConnect[Q[head]][i];
                Ans++;
            }
        }
        Order[k++] = Q[head];
        head++;
    }
    free(Indegrees);
    free(Outdegrees);
    for (int i = 0; i < numCourses; i++) {
        free(IsConnect[i]);
    }
    free(IsConnect);
    free(Q);
    if (Ans == numCourses) {
        *returnSize = numCourses;
        return Order;
    }
    else {
        free(Order);
        *returnSize = 0;
        return NULL;
    }
}

LeetCode Course Schedule II

标签:c   malloc   拓扑排序   

原文地址:http://blog.csdn.net/u012925008/article/details/45720467

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