leetcode 323.无向图中连通分量的数目 Java

这篇博客介绍了如何利用深度优先搜索(DFS)或广度优先搜索(BFS)算法解决LeetCode上的无向图连通分量数量计算问题。给出的代码模板分别使用了两种方法,通过构建邻接矩阵并进行遍历来找到所有连通分量,最终返回其数量。示例展示了不同连通性的图结构及其对应的答案。

做题博客链接

https://blog.youkuaiyun.com/qq_43349112/article/details/108542248

题目链接

https://leetcode-cn.com/problems/number-of-connected-components-in-an-undirected-graph/

描述

给定编号从 0 到 n-1 的 n 个节点和一个无向边列表(每条边都是一对节点),请编写一个函数来计算无向图中连
分量的数目。

注意:
你可以假设在 edges 中不会出现重复的边。而且由于所以的边都是无向边,[0, 1][1, 0]  相同,所以它们不会
同时在 edges 中出现。

示例

示例 1:

输入: n = 5 和 edges = [[0, 1], [1, 2], [3, 4]]

     0          3
     |          |
     1 --- 2    4 

输出: 2

示例 2:

输入: n = 5 和 edges = [[0, 1], [1, 2], [2, 3], [3, 4]]

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

输出:  1

初始代码模板

class Solution {
    public int countComponents(int n, int[][] edges) {

    }
}

代码

思路不难,直接看代码就可以。
不用数组用list也可以

BFS

class Solution {
    public int countComponents(int n, int[][] edges) {
        int[][] arr = new int[n][n];
        for (int[] cur : edges) {
            arr[cur[0]][cur[1]] = 1;
            arr[cur[1]][cur[0]] = 1;
        }

        boolean[] vis = new boolean[n];
        int res = 0;
        for (int i = 0; i < n; i++) {
            if (!vis[i]) {
                res++;
                bfs(vis, arr, i, n);
            }
        }

        return res;
    }

    private void bfs(boolean[] vis, int[][] arr, int idx, int n) {
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(idx);

        while (!queue.isEmpty()) {
            for (int size = queue.size(); size > 0; size--) {
                int loc = queue.poll();
                for (int i = 0; i < n; i++) {
                    if (arr[loc][i] == 1 && !vis[i]) {
                        vis[i] = true;
                        queue.offer(i);
                    }
                }
            }
        }
    }
}

DFS

class Solution {
    public int countComponents(int n, int[][] edges) {
        int[][] arr = new int[n][n];
        for (int[] cur : edges) {
            arr[cur[0]][cur[1]] = 1;
            arr[cur[1]][cur[0]] = 1;
        }

        boolean[] vis = new boolean[n];
        int res = 0;
        for (int i = 0; i < n; i++) {
            if (!vis[i]) {
                res++;
                dfs(vis, arr, i, n);
            }
        }

        return res;
    }

    private void dfs(boolean[] vis, int[][] arr, int idx, int n) {
        for (int i = 0; i < n; i++) {
            if (!vis[i] && arr[idx][i] == 1) {
                vis[i] = true;
                dfs(vis, arr, i, n);
            }
        }
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值