[LeetCode] 463 Island Perimeter
You 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:
解法:如果只有一个点,那么周长就是4,如果这个点和其他的一个点相邻,那么对于周长的贡献就要少一。同理,对于另外一个相邻的点,那么
贡献的周长也少一。于是先遍历,看看有多少个为1的点,算出“最大”的周长以后,减去因为相邻而减少的周长长度就可以了。
public int islandPerimeter(int[][] grid) { boolean[][] mark = new boolean[grid.length][grid[0].length]; int count = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] == 1) { mark[i][j] = true; count++; } else { mark[i][j] = false; } } } int perimeter = count * 4; System.out.println("perimeter:" + perimeter); for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (mark[i][j]) { perimeter -= neigbors(i, j, mark); //减去相邻的点 } } } return perimeter; } private int neigbors(int i, int j, boolean[][] mark) { int count = 0; for (int x = -1; x <= 1; x += 2) { int tempx = x + i; int tempy = j; if (isSafe(tempx, tempy, mark.length, mark[0].length) && mark[tempx][tempy]) { count++; } } for (int y = -1; y <= 1; y += 2) { int tempx = i; int tempy = y + j; if (isSafe(tempx, tempy, mark.length, mark[0].length) && mark[tempx][tempy]) { count++; } } System.out.printf("i:%d,j:%d\n", i, j); System.out.println("count:" + count); return count; } private boolean isSafe(int x, int y, int xlength, int ylength) { if (x < 0 || x >= xlength || y < 0 || y >= ylength) { return false; } else { return true; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?