1. 程式人生 > >演算法練習week5--leetcode684

演算法練習week5--leetcode684

一個無向圖是否存在環

演算法1:
我們知道對於環 1-2-3-4-1,每個節點的度都是2,基於此我們有如下演算法(這是類似於有向圖的拓撲排序):

  • 求出圖中所有頂點的度
  • 刪除圖中所有度 <=1 的頂點以及與該頂點相關的邊,把與這些邊相關的頂點的度減一
  • 如果還有度<=1的頂點重複步驟2
  • 最後如果還存在未被刪除的頂點,則表示有環;否則沒有環

時間複雜度為O(E+V),其中E、V分別為圖中邊和頂點的數目。

演算法2:
深度優先遍歷該圖,如果在遍歷的過程中,發現某個節點有一條邊指向已經訪問過的節點,並且這個已訪問過的節點不是當前節點的父節點(這裡的父節點表示dfs遍歷順序中的父節點),則表示存在環。但是我們不能僅僅使用一個bool陣列來標誌節點是否訪問過。

對每個節點分為三種狀態,白、灰、黑。
開始時所有節點都是白色,當開始訪問某個節點時該節點變為灰色,當該節點的所有鄰接點都訪問完,該節點顏色變為黑色。

那麼我們的演算法則為:如果遍歷的過程中發現某個節點有一條邊指向顏色為灰的節點,那麼存在環。

LeeCode題目

LeetCode題目:684. Redundant Connection
In this problem, a tree is an undirected 無向圖 graph that is connected and has no cycles.
The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, ..., N), with one additional 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] with u < v, that represents an undirected edge connecting nodes u and v.

Return an edge that can be removed so that the resulting graph is a tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. The answer edge [u, v] should be in the same format, with u < v.

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

 

Example 1

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

 

Example 2

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.
class Solution {
public:
    vector<int> findRedundantConnection(vector<vector<int>>& edges) {
        //int eSize = edges.size();
        vector<int> start(3000);
        //memset(start, 0, sizeof(int)*eSize);
        for (int i = 0; i < 3000; i++) {
            start[i] = i;
        }
        int tStart, tEnd;
        for (int i = 0; i < edges.size(); i++) {
            tStart = edges[i][0];
            tEnd = edges[i][1];

            if (start[tStart] == start[tEnd]) {
                return edges[i];
            }
            int needUpdate = start[tEnd];

            for (int j = 0; j < 3000; j++) {
                if (start[j] == needUpdate) {
                    start[j] = start[tStart];
                }
            }

        }

    }
};

Note:上述演算法的時間複雜度是O(n^2)