news 2026/4/17 23:32:13

Leetcode200岛屿数量

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Leetcode200岛屿数量

题目分析

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

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

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

代码求解

publicstaticintnumIslands(char[][]board){intn=board.length;intm=board[0].length;build(n,m,board);for(inti=0;i<n;i++){for(intj=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);}}}}returnsets;}publicstaticintMAXSIZE=100001;publicstaticint[]father=newint[MAXSIZE];publicstaticintcols;publicstaticintsets;publicstaticvoidbuild(intn,intm,char[][]board){cols=m;sets=0;for(inta=0;a<n;a++){for(intb=0,index;b<m;b++){if(board[a][b]=='1'){index=index(a,b);father[index]=index;sets++;}}}}publicstaticintindex(inta,intb){returna*cols+b;}publicstaticintfind(inti){if(i!=father[i]){father[i]=find(father[i]);}returnfather[i];}publicstaticvoidunion(inta,intb,intc,intd){intfx=find(index(a,b));intfy=find(index(c,d));if(fx!=fy){father[fx]=fy;sets--;}}
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/18 9:10:57

终极英语发音MP3下载方案:解决119,376个单词发音难题

终极英语发音MP3下载方案&#xff1a;解决119,376个单词发音难题 【免费下载链接】English-words-pronunciation-mp3-audio-download Download the pronunciation mp3 audio for 119,376 unique English words/terms 项目地址: https://gitcode.com/gh_mirrors/en/English-wo…

作者头像 李华
网站建设 2026/4/18 10:08:03

Lizard:代码复杂度的智能检测专家

Lizard&#xff1a;代码复杂度的智能检测专家 【免费下载链接】lizard A simple code complexity analyser without caring about the C/C header files or Java imports, supports most of the popular languages. 项目地址: https://gitcode.com/gh_mirrors/li/lizard …

作者头像 李华
网站建设 2026/4/18 8:08:45

3分钟掌握Ant Design X Vue:构建智能AI对话界面的完整指南

3分钟掌握Ant Design X Vue&#xff1a;构建智能AI对话界面的完整指南 【免费下载链接】ant-design-x-vue Ant Design X For Vue.&#xff08;WIP&#xff09; 疯狂研发中&#x1f525; 项目地址: https://gitcode.com/gh_mirrors/an/ant-design-x-vue 在AI技术快速发展…

作者头像 李华
网站建设 2026/4/18 5:39:05

Ant Design X Vue终极指南:5步构建企业级AI对话应用

Ant Design X Vue终极指南&#xff1a;5步构建企业级AI对话应用 【免费下载链接】ant-design-x-vue Ant Design X For Vue.&#xff08;WIP&#xff09; 疯狂研发中&#x1f525; 项目地址: https://gitcode.com/gh_mirrors/an/ant-design-x-vue 在AI技术重塑用户体验的…

作者头像 李华
网站建设 2026/4/18 5:21:27

树莓派课程设计小项目实现远程控制LED实战案例

从零开始&#xff1a;用树莓派实现远程控制LED的完整实战指南你有没有想过&#xff0c;只靠几行Python代码和一块百元级的小板子&#xff0c;就能让家里的灯在千里之外被点亮&#xff1f;这听起来像科幻片的情节&#xff0c;但在物联网时代&#xff0c;它早已成为现实。今天我们…

作者头像 李华
网站建设 2026/4/18 5:37:43

打破品牌壁垒:OpenRGB跨平台RGB灯光统一控制终极指南

打破品牌壁垒&#xff1a;OpenRGB跨平台RGB灯光统一控制终极指南 【免费下载链接】OpenRGB Open source RGB lighting control that doesnt depend on manufacturer software. Supports Windows, Linux, MacOS. Mirror of https://gitlab.com/CalcProgrammer1/OpenRGB. Release…

作者头像 李华