463. Island Perimeter
ou are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
Example:
[[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] Answer: 16 Explanation: The perimeter is the 16 yellow stripes in the image below:
题目含义:给定一个二维地图,1表示陆地,0表示水域。单元格水平或者竖直相连(不含对角线)。地图完全被水域环绕,只包含一个岛屿(也就是说,一个或者多个相连的陆地单元格)。岛屿没有湖泊(岛屿内部环绕的水域)。单元格是边长为1的正方形。地图是矩形,长宽不超过100。计算岛屿的周长。
1 public int islandPerimeter(int[][] grid) { 2 // 对于每个岛屿格子先默认加上四条边,然后检查其左面和上面是否有岛屿格子,有的话分别减去两条边,这样也能得到正确的结果, 3 int m = grid.length; 4 int n = grid[0].length; 5 if (m == 0 || n == 0) return 0; 6 int sum = 0; 7 for (int i = 0; i < m; i++) 8 for (int j = 0; j < n; j++) { 9 if (grid[i][j] == 0) continue; 10 sum += 4; 11 if (i > 0 && grid[i - 1][j] == 1) sum -= 2; 12 if (j > 0 && grid[i][j - 1] == 1) sum -= 2; 13 } 14 15 return sum; 16 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!