力扣-省份数量

思路分析

用队列实现非递归遍历,从未访问的城市入队,依次取出并标记其连通城市入队,队列为空时完成一个省份的遍历。

代码实现

java 复制代码
public int findCircleNum(int[][] isConnected) {
    // 城市数量
    int n = isConnected.length;
    // 访问标记数组,用于记录每个城市是否被访问过
    boolean[] visited = new boolean[n];
    // 定义队列用于bfs遍历
    Deque<Integer> queue = new LinkedList<>();
    // 定义相连的城市数量
    int provinceCount = 0;
    // 遍历所有城市
    for (int i = 0; i < n; i++) {
        // 若该城市未被访问过
        if (!visited[i]){
            // 标记被访问过
            visited[i] = true;
            // 该城市入队列
            queue.offer(i);
            // bfs遍历所有与该城市相连的城市
            while(!queue.isEmpty()){
                // 队首元素出队列
                Integer pop = queue.pop();
                for (int j = 0; j < n; j++) {
                    // 若该城市未被访问过且与当前城市相连
                    if (!visited[j] && isConnected[pop][j] == 1){
                        // 标记被访问过
                        visited[j] = true;
                        // 该城市入队列
                        queue.offer(j);
                    }
                }
            }
            // 遍历完所有与该城市相连的城市后,相连的城市数量加1
            provinceCount++;
        }
    }

    return provinceCount;
}

复杂度分析

  • 时间复杂度:O(n2)(遍历整个矩阵);
  • 空间复杂度:O(n)(visited 数组 + 队列,最坏情况队列存储所有城市)。

与树的bfs算法对比

这里贴出bfs算法,方便自己理解该题

java 复制代码
// 按层输出:返回二维列表,每个子列表对应一层的节点值
 public List<List<Integer>> levelOrder(TreeNode root) {
     List<List<Integer>> result = new ArrayList<>();
     if (root == null) return result;

     Queue<TreeNode> queue = new LinkedList<>();
     queue.offer(root);

     while (!queue.isEmpty()) {
         int levelSize = queue.size(); // 关键:当前层的节点数
         List<Integer> currentLevel = new ArrayList<>();

         // 遍历当前层的所有节点
         for (int i = 0; i < levelSize; i++) {
             TreeNode curr = queue.poll();
             currentLevel.add(curr.val);

             // 子节点入队(为下一层准备)
             if (curr.left != null) queue.offer(curr.left);
             if (curr.right != null) queue.offer(curr.right);
         }
         result.add(currentLevel); // 将当前层加入结果
     }
     return result;
 }

首先

  1. 二叉树的层次遍历中,根节点只有一个,所以直接就是
java 复制代码
 queue.offer(root);

 while (!queue.isEmpty()) {
 ....
 }

而本题中,多个城市相当于有多个节点,所以多了一层for循环,即第一层for循环

java 复制代码
  for (int i = 0; i < n; i++) {
  ...
  }
  1. 其次,树的层次遍历中,遍历的次数是该层的节点数,也就是
java 复制代码
for (int i = 0; i < levelSize; i++) {
	...
}

而本题中,每层的节点数都是固定也,因为题目说了是n*n的矩阵,也就是说每层都有n个节点,所以第二层循环要执行n次,也就是

java 复制代码
for (int j = 0; j < n; j++) {
...
}
相关推荐
2601_967980119 分钟前
Python闭包(Closure)详解
python·作用域·装饰器·函数式编程·闭包
AI创界者22 分钟前
ComfyUI 进阶实战:MiniMax-H3 视频人物脸部替换工作流全解析(对比 Face 5.5 实测与避坑指南)
人工智能·python·aigc
承渊政道35 分钟前
【Python编程快速上手—让繁琐工作自动化】(模式匹配与正则表达式:从找到一个号码到批量提取信息)
python·正则表达式·pycharm·自动化·模式匹配
JonaHu39 分钟前
AceDataCloud Coding Plan 多模型编程:从 Chat Completions 迁移到 Responses API 与工具调用
python·大模型·api·ai编程·acedatacloud
鲸渔1 小时前
【AI Agent系列课程23-Python 基础23】测试入门:为函数写第一个 pytest 用例
开发语言·python·pytest·ai编程
风落青芜1 小时前
排序算法(二):选择排序、堆排序与冒泡排序
c语言·开发语言·数据结构·算法·排序算法
Navigator_Z2 小时前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
h_a_o777oah2 小时前
【数据结构】FHQ Treap:无旋转的平衡 BST
数据结构·c++·算法·acm·平衡树·treap·fhq treap
fengkai45452 小时前
Python运维实战
运维·开发语言·python·ssh·sftp·paramiko
用户45428451062812 小时前
一张 3000×2000 的 PSD 为什么 86MB:从体积构成到上传墙
python