Redundant Connection II 解法

Redundant Connection II 解法


第 19 周题目
难度:Hard
LeetCode题号:685

题目

Description:

In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.

The given input is a directed graph that started as a rooted tree with N nodes (with distinct values 1, 2, …, N), with one additional directed edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed.

The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] that represents a directed edge connecting nodes u and v, where u is a parent of child v.

Return an edge that can be removed so that the resulting graph is a rooted tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array.

Example1:
Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given directed graph will be like this:
1
/ \
v v
2–>3

Example2:
Input: [[1,2], [2,3], [3,4], [4,1], [1,5]]
Output: [4,1]
Explanation: The given directed graph will be like this:
5 <- 1 -> 2
^ |
| v
4 <- 3


思考

思路:归纳有3种情况
* 1. 有2个parent节点,无环
* 2. 只有环
* 3. 有2个parent节点,有环
*
* 最开始想找到所有的candidate,然后注意去掉判断是否合法
* 其实也可以直接就这样先求有没有2个parent的节点和有没有环


代码

class Solution {
private:
    struct Node{
        vector<int> from; //parent(s), at most one node has 2 parents in a graph
        vector<int> to; //children, can have many children
    };
    unordered_map<int,Node> getNode;
    unordered_map<int,unordered_map<int,int>> edgeOrder;

public:
    vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) {
        //construct the graph, and record the node which has 2 parents if possible
        int N = edges.size();
        for(int n=1; n<=N; ++n)
            getNode[n] = Node();
        int node2parents = -1;
        for(int i=0; i<N; ++i){
            int p = edges[i][0];
            int c = edges[i][1];
            edgeOrder[p][c] = i;
            getNode[p].to.push_back(c);
            getNode[c].from.push_back(p);
            if(getNode[c].from.size()==2) //we find a node with 2 parents
                node2parents = c;
        }

        //doing DFS to find the loop if loop exists
        vector<int> status(N+1,0); // status 0,1,2 ==> 0:unvisited, 1:visiting, 2:visited
        stack<int> loop;
        bool loopfound = false;
        for(int i=1; i<=N; ++i){
            if(loopfound)   break;
            if(status[i] == 0){ //DFS started with node i
                status[i] = 1;
                stack<int> stk({i});
                DFS(stk,status,loopfound,loop);
                status[i] = 2;
            }
        }

        if(!loopfound){ // Case 1
            int parent1 = getNode[node2parents].from[0];
            int parent2 = getNode[node2parents].from[1];
            return (edgeOrder[parent1][node2parents] > edgeOrder[parent2][node2parents]) ?
                    vector<int>({parent1,node2parents}) : vector<int>({parent2,node2parents});
        }

        int last_occur_order = 0;
        vector<int> last_occur_edge;
        int begin = loop.top();
        while(!loop.empty()){
            int child = loop.top();
            loop.pop();
            int parent = loop.top();
            if(node2parents != -1 && child == node2parents) // Case 2
                return vector<int>({parent,child});
            int order = edgeOrder[parent][child];
            if(order > last_occur_order){
                last_occur_order = order;
                last_occur_edge = vector<int>({parent,child});
            }
            if(parent == begin)
                break; //loop ends
        }

        return last_occur_edge; // Case 3
    }

    void DFS(stack<int>& stk, vector<int>& status, bool& flag, stack<int>& loop){
        for(int c : getNode[stk.top()].to){
            if(flag)   return;
            if(status[c] == 1){
                stk.push(c);
                loop = stk;
                flag = true;
                return;
            }
            else if(status[c] == 0){
                stk.push(c);
                status[c] = 1;
                DFS(stk,status,flag,loop);
                status[c] = 2;
                stk.pop();
            }
        }
    }
};
//
//                       _oo0oo_
//                      o8888888o
//                      88" . "88
//                      (| -_- |)
//                      0\  =  /0
//                    ___/`---'\___
//                  .' \\|     |// '.
//                 / \\|||  :  |||// \
//                / _||||| -:- |||||- \
//               |   | \\\  -  /// |   |
//               | \_|  ''\---/''  |_/ |
//               \  .-\__  '-'  ___/-. /
//             ___'. .'  /--.--\  `. .'___
//          ."" '<  `.___\_<|>_/___.' >' "".
//         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
//         \  \ `_.   \_ __\ /__ _/   .-` /  /
//     =====`-.____`.___ \_____/___.-`___.-'=====
//                       `=---='
//
//
//     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//               佛祖保佑         永无BUG
//
//
//
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值