leetcode 岛屿的周长

该篇博客介绍了如何计算给定二维网格中岛屿的周长。算法通过遍历网格,判断每个单元格是否为陆地,并根据陆地的位置更新周长计数。算法复杂度为O(n*m),其中n和m分别代表网格的行数和列数。此问题涉及到了图论和数组遍历的知识。
摘要由CSDN通过智能技术生成

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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值