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

做题博客链接

https://blog.csdn.net/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);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43349112/article/details/115256617