Leetcode200岛屿数量

题目分析

要区分二维矩阵中的每个1,需要将二维问题转化为一维编号问题。

如果矩阵有m列,位于第i行、第j列的元素对应的一维编号为i乘以m加j。

先将所有的1建成小集合,遍历矩阵,遇到1时,如果其左边或者上边有1则进行合并,最后统计并查集中集合的数量就是岛的数量。

代码求解

java 复制代码
public static int numIslands(char[][] board){
		int n = board.length;
		int m = board[0].length;

		build(n,m,board);
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				if(board[i][j]=='1'){
					if(j>0&&board[i][j-1]=='1'){
						union(i,j,i,j-1);
					}

					if(i>0&&board[i-1][j]=='1'){
						union(i,j,i-1,j);
					}
				}
			}
		}
		return sets;
	}

	public static int MAXSIZE = 100001;
	public static int[] father = new int[MAXSIZE];
	public static int cols;
	public static int sets;

	public static void build(int n,int m,char[][] board){
		cols = m;
		sets = 0;
		for(int a=0;a<n;a++){
			for(int b=0,index;b<m;b++){
				if(board[a][b]=='1'){
					index = index(a,b);
					father[index]=index;
					sets++;
				}
			}
		}
	}

	public static int index(int a,int b){
		return a*cols+b;
	}

	public static int find(int i){
		if(i!=father[i]){
			father[i]=find(father[i]);
		}
		return father[i];
	}

	public static void union(int a,int b,int c,int d){
		int fx = find(index(a, b));
		int fy = find(index(c, d));
		if(fx!=fy){
			father[fx]=fy;
			sets--;
		}
	}
相关推荐
keyipatience6 小时前
线程栈与TLS和线程互斥
java·linux·服务器·开发语言·ubuntu
我的xiaodoujiao6 小时前
快速学习Python基础知识详细图文教程9--函数进阶
开发语言·python·学习·测试工具
weixin_408099677 小时前
2026 图片去水印 API 接口完全指南:一键去除图片水印(附 Python/Java/PHP/C# 示例)
java·python·php·图片处理·api调用·图片去水印·石榴智能
爱喝水的鱼丶7 小时前
SAP-ABAP:ALV通用封装实践——搭建可复用的ALV开发工具类,减少80%重复代码
开发语言·性能优化·sap·abap·erp·alv
钱六两7 小时前
#3、SpringAI 接入deepSeek大模型(喂饭版)
java·spring boot·ai编程
脱胎换骨-军哥7 小时前
C++/Rust无缝互操作:混合系统新常态
开发语言·c++·rust
songroom8 小时前
Kimi K3:Rust封装XTP接口详细教程实践
开发语言·后端·rust
kebeiovo8 小时前
游戏服务端开发:Actor模型详解(Go语言)
开发语言·后端·golang
迷途呀8 小时前
Python:函数中的参数类型
开发语言·笔记·python·langchain·nlp
null_178 小时前
IntelliJ IDEA 极致流畅配置方案:Ultra 9 285K + 64GB 内存实测
java·ide·intellij-idea