首页 > 其他 > 详细

323. Number of Connected Components in an Undirected Graph 连通图的数量

时间:2021-08-30 12:17:12      阅读:13      评论:0      收藏:0      [点我收藏+]

You have a graph of n nodes. You are given an integer n and an array edges where edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph.

Return the number of connected components in the graph.

 

Example 1:

技术分享图片

Input: n = 5, edges = [[0,1],[1,2],[3,4]]
Output: 2

Example 2:

技术分享图片

Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
Output: 1

dfs的思路是:无论递归栈多深,都只计算为1

class Solution {
    public int countComponents(int n, int[][] edges) {
        List<Integer>[] graph = new List[n];
        for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();
        for (int[] e : edges) {
            graph[e[0]].add(e[1]);
            graph[e[1]].add(e[0]);
        }
        int components = 0;
        boolean[] visited = new boolean[n];
        for (int v = 0; v < n; v++) components += dfs(v, graph, visited);
        return components;
    }
    int dfs(int u, List<Integer>[] graph, boolean[] visited) {
        if (visited[u]) return 0;
        visited[u] = true;
        for (int v : graph[u]) dfs(v, graph, visited);
        return 1;
    }
}

 

 

323. Number of Connected Components in an Undirected Graph 连通图的数量

原文:https://www.cnblogs.com/immiao0319/p/15195894.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!