[Leetcode] 323. Number of Connected Components in an Undirected Graph 解题报告

题目

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.

Example 1:

     0          3
     |          |
     1 --- 2    4

Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], return 2.

Example 2:

     0           4
     |           |
     1 --- 2 --- 3

Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [3, 4]], return 1.

Note:
You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.

思路

一道难度适中的Union-Find题目。这类题目也有套路:首先为每个顶点初始化一个单独的集合;然后遍历,每次遇到一个边,就把边的两个顶点所属的集合进行合并,同时总的连通图数量减1。注意判断两个顶点是否属于同一个集合的经典代码,个人感觉应该背下来^_^。

这道题目用BFS和DFS也可以求解,但代码要相对复杂一些。

代码

class Solution {
public:
    int countComponents(int n, vector>& edges) {
        vector parents(n);
        for (int i = 0; i < n; ++i) {
            parents[i] = i;
        }
        int ret = n;
        for (int i = 0; i < edges.size(); ++i) {
            int par1 = edges[i].first, par2 = edges[i].second;
            while (par1 != parents[par1]) {
                par1 = parents[par1];
            }
            while (par2 != parents[par2]) {
                par2 = parents[par2];
            }
            if (par1 != par2) {
                parents[par2] = par1;
                --ret;
            }
        }
        return ret;
    }
};

你可能感兴趣的:(IT公司面试习题)