代码改变世界

[LeetCode]Number of Islands

  庸男勿扰  阅读(194)  评论(0编辑  收藏  举报

原题链接:https://leetcode.com/problems/number-of-islands/

题意描述:

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

题解:

此题的大意就是找出一个图中的联通区域,一个联通子图便认为是一个岛屿。显然就是对每一个未访问过且是陆地的点进行上下左右搜索,这样即可找到一个联通子图。然后对全图都这样做一遍,便能找到所有的,即结果。代码如下:

复制代码
 1 public class Solution {
 2     public static boolean flag = false;
 3 
 4     public int numIslands(char[][] grid) {
 5         boolean[][] visited = new boolean[grid.length][];
 6         for (int i = 0; i < grid.length; i++)
 7             visited[i] = new boolean[grid[i].length];
 8         for (int i = 0; i < grid.length; i++) {
 9             for (int j = 0; j < grid[0].length; j++) {
10                 visited[i][j] = false;
11             }
12         }
13         int res = 0;
14         for (int i = 0; i < grid.length; i++) {
15             for (int j = 0; j < grid[0].length; j++) {
16                 flag = false;
17                 process(i, j, grid, visited);
18                 if (flag)
19                     res++;
20             }
21         }
22         return res;
23     }
24 
25     public void process(int i, int j, char[][] grid, boolean[][] visited) {
26         if (grid[i][j] != '1' || visited[i][j])
27             return;
28         visited[i][j] = true;
29         flag = true;
30         if (j >= 1)
31             process(i, j - 1, grid, visited);
32         if (i >= 1)
33             process(i - 1, j, grid, visited);
34         if(i+1<grid.length)
35             process(i + 1, j, grid, visited);
36         if(j+1<grid[0].length)
37             process(i, j + 1, grid, visited);
38     }
39 }
复制代码

 

编辑推荐:
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
阅读排行:
· “你见过凌晨四点的洛杉矶吗?”--《我们为什么要睡觉》
· C# 从零开始使用Layui.Wpf库开发WPF客户端
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· C#/.NET/.NET Core技术前沿周刊 | 第 31 期(2025年3.17-3.23)
· 接口重试的7种常用方案!
点击右上角即可分享
微信分享提示