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--;
		}
	}
相关推荐
霸道流氓气质2 分钟前
幂等性与 Upsert:防止重复操作产生副作用的技术
开发语言·php
牛奔13 分钟前
mise 管理多版本 Go 项目
开发语言·前端·chrome·后端·golang
huaweichenai27 分钟前
spring boot对接阿里短信
java·spring boot
波力海苔夹心脆67527 分钟前
C# 视觉检测实战:PLC 按钮触发 VisionPro 检测,OK 亮灯 / NG 灭灯(西门子 PLC,含界面显示与图片存档)
开发语言·经验分享·c#·自动化·视觉检测·.net
KING-WU51228 分钟前
Linux 工具之Make 与 Makefile
java·linux·服务器
2601_9628857240 分钟前
如何用 Python 计算 BBI 多空指标?
开发语言·python
马剑威(威哥爱编程)1 小时前
【AI全栈后端12-08】Spring Boot 用 MCP 统一接入内部系统:让 AI 接一次,全公司复用
java·人工智能·spring boot
顽疲1 小时前
从零用 Java 实现小红书 SpringBoot Vue UniApp(23)笔记话题多对多:一条笔记进多个话题池
java·vue.js·spring boot
老王爱玩车1 小时前
动态内存管理
c语言·开发语言·学习·面试
I'm Jie1 小时前
【开源】7 天,我用 Rust 复刻了 FinalShell!Rhost v1.0.0 发布
开发语言·rust·开源