[JavaScript 刷题] 矩阵 - 岛屿的周长, leetcode 463

Posted GoldenaArcher

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[JavaScript 刷题] 矩阵 - 岛屿的周长, leetcode 463相关的知识,希望对你有一定的参考价值。

[javascript 刷题] 矩阵 - 岛屿的周长, leetcode 463

github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。

题目地址:463. Island Perimeter

题目

如下:

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.

解题思路

其实 lc 给的图片就挺能解释一切了:

这里要返回的就是黄色的边框,也就是岛屿的周长。

岛屿的周长可以通过计算每个网格与相邻的网格而成,,一个独自美好的网格周长为 4——4 个边都能被列入计算;一个有邻居的网格就要与邻居共享边框,也就是图中黑色的部分。邻居越多,不属于自己的边框就越多。

这道题刚开始想过是不是要用 DFS/BFS 做,后来看了下题目就觉得没什么必要,直接遍历整个 grid,返回周长即可。

如果有需要计算岛屿周长最大的需求,那就必须要用 BFS/DFS 去做了,不过也可以嵌套 200. 岛屿数量 & 695. 岛屿的最大面积 的做法,只是面积换成了周长而已。

使用 JavaScript 解题

/**
 * @param number[][] grid
 * @return number
 */
var islandPerimeter = function (grid) 
  const directions = [
    [1, 0],
    [-1, 0],
    [0, 1],
    [0, -1],
  ];

  const checkNeighbors = (r, c) => 
    let neighbors = 0;

    for (const [ri, ci] of directions) 
      const rc = r + ri,
        cc = c + ci;
      if (grid[rc] && grid[rc][cc] === 1) 
        neighbors++;
      
    

    return neighbors;
  ;

  let perimeter = 0;

  for (let i = 0; i < grid.length; i++) 
    for (let j = 0; j < grid[i].length; j++) 
      if (grid[i][j] === 1) 
        perimeter += 4 - checkNeighbors(i, j);
      
    
  

  return perimeter;
;

以上是关于[JavaScript 刷题] 矩阵 - 岛屿的周长, leetcode 463的主要内容,如果未能解决你的问题,请参考以下文章

[JavaScript 刷题] 矩阵 - 重塑矩阵, leetcode 566

[JavaScript 刷题] 矩阵 - 重塑矩阵, leetcode 566

java刷题--200岛屿数量

[JavaScript 刷题] 矩阵 - 转置矩阵, leetcode 867

力扣刷题:岛屿数量(java实现)

力扣刷题:岛屿数量(java实现)