这是问题(https://leetcode.com/problems/course-schedule-ii/description/)。
我的解决方案来自“算法简介”。
使用DFS算法。并用白色,灰色和黑色为节点着色。


将所有节点标记为白色。
发现节点后,标记为灰色。
节点完成后,标记为黑色。
当边缘向后时,意味着相邻节点之间为灰色。它有一个圆,应该为null。


但是我通过了大多数情况。但是其中一些不是。
有人可以帮我吗?

代码:

class Solution {
public:
    enum {WHITE, GRAY, BLACK};

    vector<vector<int>> graph;
    vector<int> colors;
    list<int> topo;

    void add_edge(vector<vector<int>>& graph, pair<int, int>& p) {
        graph[p.second].push_back(p.first);
    }
    bool visit(vector<vector<int>>& graph, int i) {
        if (colors[i] == WHITE) {
            colors[i] = GRAY;
            bool ret = true;

            for (int j = 0; j < graph[i].size(); j++) {
                if (colors[graph[i][j]] == WHITE)
                    ret = ret && visit(graph, graph[i][j]);
                else if (colors[graph[i][j]] == GRAY)
                    ret =  false;
                else
                    ret =  false;

            }

            colors[i] = BLACK;
            topo.push_front(i);
            return ret;
        }

        return true;
    }

    bool dfs(vector<vector<int>>& graph) {
        for (int i = 0; i < graph.size(); i++)
            if (!visit(graph, i))
                return false;
        return true;
    }



public:
    vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
        graph.resize(numCourses, {});
        colors.resize(numCourses, WHITE);

        for (auto& pre: prerequisites)
            add_edge(graph, pre);

        if (!dfs(graph))
            return {};

        vector<int> ret (topo.begin(),topo.end());
        return ret;
    }
};

最佳答案



        for (int j = 0; j < graph[i].size(); j++) {
            if (colors[graph[i][j]] == WHITE)
                ret = ret && visit(graph, graph[i][j]);
            else if (colors[graph[i][j]] == GRAY)
                ret =  false;
            else
                ret =  false;
        }


最后一个是当节点为BLACK时,这意味着它已经被处理并压入结果。因此,它不会使图形无效。只需删除最后一个,它将起作用。像这样:

        for (int j = 0; j < graph[i].size(); j++) {
            if (colors[graph[i][j]] == WHITE)
                ret = ret && visit(graph, graph[i][j]);
            else if (colors[graph[i][j]] == GRAY)
                ret =  false;
            /* else
                ret =  false; */
        }

关于c++ - Leetcode210。为什么我的代码在特定情况下是错误的?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46049480/

10-13 07:45
查看更多