mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
新增 463.岛屿的周长 JavaScript版本
This commit is contained in:
@ -120,6 +120,55 @@ Python:
|
||||
Go:
|
||||
|
||||
JavaScript:
|
||||
```javascript
|
||||
//解法一
|
||||
var islandPerimeter = function(grid) {
|
||||
// 上下左右 4 个方向
|
||||
const dirx = [-1, 1, 0, 0], diry = [0, 0, -1, 1];
|
||||
const m = grid.length, n = grid[0].length;
|
||||
let res = 0; //岛屿周长
|
||||
for(let i = 0; i < m; i++){
|
||||
for(let j = 0; j < n; j++){
|
||||
if(grid[i][j] === 1){
|
||||
for(let k = 0; k < 4; k++){ //上下左右四个方向
|
||||
// 计算周边坐标的x,y
|
||||
let x = i + dirx[k];
|
||||
let y = j + diry[k];
|
||||
// 四个方向扩展的新位置是水域或者越界就会为周长贡献1
|
||||
if(x < 0 // i在边界上
|
||||
|| x >= m // i在边界上
|
||||
|| y < 0 // j在边界上
|
||||
|| y >= n // j在边界上
|
||||
|| grid[x][y] === 0){ // (x,y)位置是水域
|
||||
res++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
//解法二
|
||||
var islandPerimeter = function(grid) {
|
||||
let sum = 0; // 陆地数量
|
||||
let cover = 0; // 相邻数量
|
||||
for(let i = 0; i < grid.length; i++){
|
||||
for(let j = 0; j <grid[0].length; j++){
|
||||
if(grid[i][j] === 1){
|
||||
sum++;
|
||||
// 统计上边相邻陆地
|
||||
if(i - 1 >= 0 && grid[i-1][j] === 1) cover++;
|
||||
// 统计左边相邻陆地
|
||||
if(j - 1 >= 0 && grid[i][j-1] === 1) cover++;
|
||||
// 为什么没统计下边和右边? 因为避免重复计算
|
||||
}
|
||||
}
|
||||
}
|
||||
return sum * 4 - cover * 2;
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
|
Reference in New Issue
Block a user