LeetCode 323. Number of Connected Components in an Undirected Graph(连通分量)

原题网址:https://leetcode.com/problems/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.

方法一:深度优先搜索+并查集。

public class Solution {
    private int components;
    private void find(int prev, int node, boolean[] visit, int[] roots, List[] graph) {
        if (visit[node]) return;
        if (prev != -1) {
            int pid = root(roots, prev);
            int rid = root(roots, node);
            if (pid != rid) {
                roots[pid] = rid;
                components --;
            }
        }
        visit[node] = true;
        for(int i=0; i[] graph = new List[n];
        for(int i=0; i();
        for(int[] edge: edges) {
            graph[edge[0]].add(edge[1]);
            graph[edge[1]].add(edge[0]);
        }
        int[] roots = new int[n];
        for(int i=0; i

方法二:使用并查集来标记图的连通分量。

public class Solution {
    private int root(int[] roots, int i) {
        while (roots[i] != i) i = roots[roots[i]];
        return i;
    }
    public int countComponents(int n, int[][] edges) {
        int count = n;
        int[] roots = new int[n];
        for(int i=0; i

你可能感兴趣的:(图,连通,连通性,连通分量,并查集,拓扑排序)