Open Tcdian opened 4 years ago
/**
* @param {number[][]} grid
* @return {number}
*/
var islandPerimeter = function(grid) {
let perimeter = 0;
const direction = [-1, 0, 1, 0, -1];
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[0].length; j++) {
if (grid[i][j] === 1) {
for (let d = 0; d < 4; d++) {
const directionX = i + direction[d];
const directionY = j + direction[d + 1];
if (
directionX < 0 || directionX >= grid.length
|| directionY < 0 || directionY >= grid[0].length
|| grid[directionX][directionY] === 0
) {
perimeter += 1;
}
}
}
}
}
return perimeter;
};
function islandPerimeter(grid: number[][]): number {
let perimeter = 0;
const direction = [-1, 0, 1, 0, -1];
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[0].length; j++) {
if (grid[i][j] === 1) {
for (let d = 0; d < 4; d++) {
const directionX = i + direction[d];
const directionY = j + direction[d + 1];
if (
directionX < 0 || directionX >= grid.length
|| directionY < 0 || directionY >= grid[0].length
|| grid[directionX][directionY] === 0
) {
perimeter += 1;
}
}
}
}
}
return perimeter;
};
463. Island Perimeter
给定一个包含
0
和1
的二维网格地图,其中1
表示陆地0
表示水域。网格中的格子水平和垂直方向相连(对角线方向不相连)。整个网格被水完全包围,但其中恰好有一个岛屿(或者说,一个或多个表示陆地的格子相连组成的岛屿)。
岛屿中没有“湖”(“湖” 指水域在岛屿内部且不和岛屿周围的水相连)。格子是边长为
1
的正方形。网格为长方形,且宽度和高度均不超过100
。计算这个岛屿的周长。Example
Explanation: The perimeter is the 16 yellow stripes in the image below: