You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 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", meaning the water inside 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.
func islandPerimeter(grid [][]int) int {
var land, border int
for i := 0; i < len(grid); i++ {
for j := 0; j < len(grid[0]); j++ {
if grid[i][j] == 1 {
land++
if i < len(grid)-1 && grid[i+1][j] == 1 {
border++
}
if j < len(grid[0])-1 && grid[i][j+1] == 1 {
border++
}
}
}
}
return 4*land - 2*border
}
该篇博客介绍了如何计算给定二维网格中岛屿的周长。算法通过遍历网格,判断每个单元格是否为陆地,并根据陆地的位置更新周长计数。算法复杂度为O(n*m),其中n和m分别代表网格的行数和列数。此问题涉及到了图论和数组遍历的知识。
546

被折叠的 条评论
为什么被折叠?



