0%

island-perimeter

Island Perimeter – LeetCode 463

Problem

Description

You are given a map in form of a two-dimensional integer grid where 1 represents land and 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” (water inside that 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.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int get(vector<vector<int>>& grid,int x,int y,int limitx, int limity){
int sum = 0;
sum += x ? !(grid[x - 1][y]) : 1;
sum += y ? !(grid[x][y - 1]) : 1;
sum += x + 1 == limitx ? 1 : !(grid[x + 1][y]);
sum += y + 1 == limity ? 1 : !(grid[x][y + 1]);
return sum;
}

int islandPerimeter(vector<vector<int>>& grid) {
int limitx = grid.size(), limity = grid[0].size(), sum = 0;
for(int i = 0; i != limitx; ++i){
for(int j = 0; j != limity; ++j)
sum += grid[i][j] ? get(grid,i,j,limitx,limity) : 0;
}
return sum;
}
};

思路

统计每个上下左右的个数就行了。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$193$ ms,排名$78.31\%$

Better

思路

写法更漂亮。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$153$ ms,排名$39.72\%$

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
if (grid.empty() || grid[0].empty()) return 0;
int m = grid.size(), n = grid[0].size(), res = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 0) continue;
if (j == 0 || grid[i][j - 1] == 0) ++res;
if (i == 0 || grid[i - 1][j] == 0) ++res;
if (j == n - 1 || grid[i][j + 1] == 0) ++res;
if (i == m - 1 || grid[i + 1][j] == 0) ++res;
}
}
return res;
}
};