463.岛屿的面积(javascript)463.IslandPerimeter

原创
小哥 3年前 (2022-11-10) 阅读数 6 #大杂烩

给定一个 row x col 二维网格图 grid ,其中:grid[i][j] = 1 代表土地, grid[i][j] = 0 表示水域。

网格中的网格 水平和垂直 方向连接(对角方向不连接)。整个网格完全被水包围,但其中只有一个岛(或者,换句话说,一个或多个代表陆地网格的岛屿)。

岛上没有“湖” 指的是岛内的水域,不与岛周围的水域相连)。网格为边长。 1 广场网格为矩形,宽度和高度均不超过 100 .计算岛的周长。

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.

示例 1:

输入:grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
输出:16
说明:其周长如上图所示 16 黄色边缘

示例 2:

输入:grid = [[1]]
输出:4

示例 3:

输入:grid = [[1,0]]
输出:4

提示:

  • row == grid.length
  • col == grid[i].length
  • 1 <= row, col <= 100
  • grid[i][j] 为 0 或 1

解题思路

原则上,一块土地将带来 4 周长,但岛上的陆地是有边界的,每个边界都会被减去。 2 个边长。

所以,总周长 = 4 土地个数 - 2 边界边数。

穿越矩阵,穿越陆地 land++,如果它是正确的/那么底部也是陆地 border++,将结束子代遍历到公式中。

需要删除重复添加的边

var islandPerimeter = function (grid) {
    let land = 0
    let border = 0
    let rLen = grid.length
    let cLen = grid[0].length
    for (let i = 0; i < rLen; i++) {
        for (let  j= 0; j < cLen; j++) {
            if(grid[i][j]==1){
                land++
                if(i+1

leetcode: https://leetcode-cn.com/problems/island-perimeter/

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除