​LeetCode刷题实战547:省份数量

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 省份数量,我们先来看题面:

https://leetcode-cn.com/problems/number-of-provinces/

There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.

A province is a group of directly or indirectly connected cities and no other cities outside of the group.

You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.

Return the total number of provinces.

有 n 个城市,其中一些彼此相连,另一些没有相连。如果城市 a 与城市 b 直接相连,且城市 b 与城市 c 直接相连,那么城市 a 与城市 c 间接相连。

省份 是一组直接或间接相连的城市,组内不含其他没有相连的城市。

给你一个 n x n 的矩阵 isConnected ,其中 isConnected[i][j] = 1 表示第 i 个城市和第 j 个城市直接相连,而 isConnected[i][j] = 0 表示二者不直接相连。

返回矩阵中 省份 的数量。

示例                         

e28d24500291b68dc1617f3c48f757fb.png

解题

https://www.jianshu.com/p/ad8f5413a7ea

运用BFS的方法,先找到一条路径的所有连接城市,然后+1,接着找下一条。

首先审题,参数矩阵是一个方阵且是对称矩阵,对角线都是1代表自身相连。所以我们从0开始遍历,代表第一个城市,先判断是否访问,未被访问就入队,然后寻找所有直接和间接相连接的城市,即矩阵值为1且未访问的城市,然后入队。

class Solution {
    public int findCircleNum(int[][] isConnected) {
        int n = isConnected.length;
        int res = 0;

        // 记录已访问城市
        List<Integer> visited = new ArrayList<>();
        // 记录路径
        Queue<Integer> queue = new LinkedList<>();

        for (int i = 0; i < n; i++) {
            // 未访问城市入队
            if (!visited.contains(i)) {
                queue.offer(i);
                while (!queue.isEmpty()) {
                    int cur = queue.poll();
                    // 当前城市已访问
                    visited.add(cur);
                    // 寻找连接城市
                    for (int j = 0; j < n; j++) {
                        if (isConnected[cur][j] == 1 && !visited.contains(j)) {
                            // 连接城市入队
                            queue.offer(j);
                        }
                    }
                }
                res++;
            }
        }
        return res;
    }
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-540题汇总,希望对你有点帮助!

LeetCode刷题实战541:反转字符串 II

LeetCode刷题实战542:01 矩阵

LeetCode刷题实战543:二叉树的直径

LeetCode刷题实战544:输出比赛匹配对

LeetCode刷题实战545:二叉树的边界

LeetCode刷题实战546:移除盒子

ea28e5f27b54909479462d560e0a395b.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值