[leetcode] Redundant Connection II

题目

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.


Example 1:
Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given directed graph will be like this:


Example 2:
Input: [[1,2], [2,3], [3,4], [4,1], [1,5]]
Output: [4,1]
Explanation: The given directed graph will be like this:


Note:

  • The size of the input 2D-array will be between 3 and 1000.
  • Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.

思路

这道题的情况可以分为下面几种:

情况例子处理
图中没有环[[1,2],[1,3],[2,3]]删除两条路径中较晚的边
图中有环,其中一个点有两个父节点[[1,2],[2,3],[3,1],[4,1]]删除存在于环内,指向双父亲节点的边
图中有环,所有节点都只有一个父节点[[1,2],[2,3],[3,1],[1,4]]删除环中最晚的边

代码

class Solution {
public:
    vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) {
        // 生成图
        // 表示边出现的顺序
        map<pair<int, int>, int> edgeOrder;
        // 该问题中点的个数恰好等于边的个数
        int N = edges.size();
        // 但问题中的序号从1开始,因此置空邻接矩阵零号位置
        vector<vector<int>> ajacency(N + 1, vector<int>());
        vector<vector<int>> from(N + 1, vector<int>());
        for (int i = 0; i < N; ++i) {
            auto edge = edges[i];
            ajacency[edge[0]].push_back(edge[1]);
            from[edge[1]].push_back(edge[0]);
            edgeOrder[pair<int, int>(edge[0], edge[1])] = i;
        }
        // 找到双父母的节点
        int nodeWithTwoParents = -1;
        int parent1 = -1;
        int parent2 = -1;
        for(int i = 1; i <= N; ++i) {
            if(from[i].size() == 2) {
                nodeWithTwoParents = i;
                parent1 = from[i][0];
                parent2 = from[i][1];
                break;
            }
        }

        // 寻找图中是否有环
        bool hasCircle = false;
        vector<int> circle;

        typedef enum {
            WAITING,
            VISITING,
            VISITED
        } Status;
        vector<Status> status(N + 1, WAITING);

        // DFS返回值是bool,表示点begin是否在环内
        function<bool (int)> DFS;
        DFS = [&DFS, &status, &hasCircle, 
                &nodeWithTwoParents, &ajacency,
                &circle
            ] (int begin) {
            status[begin] = VISITING;
            bool InCircle = false; // 判断begin是否在环内
            for (auto child : ajacency[begin]) {
                switch (status[child]) {
                    case WAITING:
                        if(DFS(child)) {
                            // 子迭代中发现有环,且仍未到达环双父母的点
                            circle.push_back(child);
                            if(begin != circle.front()) {
                                InCircle = true;
                            }
                        }
                        break;
                    case VISITING: // 有环
                        circle.push_back(child);
                        hasCircle = true;
                        InCircle = true;
                        break;
                    case VISITED:
                    default:
                        break;
                }
            }
            status[begin] = VISITED;
            return InCircle;
        };
        DFS(1);

        vector<int> ans1 = vector<int>({ parent1, nodeWithTwoParents });
        vector<int> ans2 = vector<int>({ parent2, nodeWithTwoParents });

        // 无环,删除双父母边中较晚的一条
        if(!hasCircle) {
            return edgeOrder[pair<int, int>(parent1, nodeWithTwoParents)] 
                    > edgeOrder[pair<int, int>(parent2, nodeWithTwoParents)] 
                ? ans1
                : ans2;
        }

        // 有环
        if(nodeWithTwoParents != -1) {
            for(auto v : circle) {
                if(v == parent1) {
                    return ans1;
                } else if(v == parent2) {
                    return ans2;
                }
            }
        } else {
            // 删除环内最早的边 
            int earlyOrder = 0;
            vector<int> ans(2, 0);
            for(int i = 0; i != circle.size(); ++i) {
                int _from = circle[(i + 1) % circle.size()];
                int _to = circle[i];
                int order = edgeOrder[pair<int, int>(_from, _to)];
                if(order > earlyOrder) {
                    ans[0] = _from;
                    ans[1] = _to;
                    earlyOrder = order;
                }
            }
            return ans;
        }
        return vector<int>(2, INT_MAX);
    }
};

代码中的细节

邻接表中的空位

由于题目给的数字从1开始,为了访问方便,我们把邻接表的第一位置空

vector<vector<int>> ajacency(N + 1, vector<int>());

hasCircle和InCircle的区别

代码中出现了两个类似的bool变量hasCircle和InCircle,前者指在遍历过程中发现了环,后者指遍历到此处时,begin点仍然在环内。

判断图中是否有环

在DFS中设置节点的三种状态:

typedef enum {
    WAITING,
    VISITING,
    VISITED
} Status;

WAITING指节点已经被访问
VISITING指节点已访问,但仍存在未访问完的子节点
VISITED指节点已访问,而且其子节点也已经访问完成

如何找到环

在DFS迭代中,节点向下个层迭代时,如果下一层报告发现了环,那么当前节点会把报告的子节点插入到circle中。另外,当发现自身已经存在于circle时,不再通知上层把自己放入circle,因为这个工作已经由发现环的第一个节点完成了。

case WAITING:
	if(DFS(child)) {
	    // 子迭代中发现有环,且仍未到达环双父母的点
	    circle.push_back(child);
	    if(begin != circle.front()) {
	        InCircle = true;
	    }
	}
	break;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值