mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
463 岛屿的周长
更新Java的方法二
This commit is contained in:
@ -118,6 +118,27 @@ class Solution {
|
|||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 解法二
|
||||||
|
class Solution {
|
||||||
|
public int islandPerimeter(int[][] grid) {
|
||||||
|
// 计算岛屿的周长
|
||||||
|
// 方法二 : 遇到相邻的陆地总周长就-2
|
||||||
|
int landSum = 0; // 陆地数量
|
||||||
|
int cover = 0; // 相邻陆地数量
|
||||||
|
for (int i = 0; i < grid.length; i++) {
|
||||||
|
for (int j = 0; j < grid[0].length; j++) {
|
||||||
|
if (grid[i][j] == 1) {
|
||||||
|
landSum++;
|
||||||
|
// 统计上面和左边的相邻陆地
|
||||||
|
if(i - 1 >= 0 && grid[i-1][j] == 1) cover++;
|
||||||
|
if(j - 1 >= 0 && grid[i][j-1] == 1) cover++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return landSum * 4 - cover * 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
Reference in New Issue
Block a user