GuoXin Li's Blog

LeetCode463. Island Perimeter

字数统计: 259阅读时长: 1 min
2020/03/02 Share

463. Island Perimeter

463. Island Perimeter

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.

Example:

Input:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]

Output: 16

Explanation: The perimeter is the 16 yellow stripes in the image below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
if(grid.empty()) return 0;
int m = grid.size();
int n = grid[0].size();
int area = 0, nei = 0;
for(int y = 0; y < m; ++y){
for(int x = 0; x < n; ++x){
if(grid[y][x] == 1){
area++;
if(y > 0 &&grid[y-1][x] == 1 ) nei++;
if(y < m-1 && grid[y+1][x] == 1) nei++;
if(x > 0 && grid[y][x-1]==1) nei++;
if(x < n-1&& grid[y][x+1] == 1) nei++;
}
}
}
return area*4 - nei;
}
};

Time Complexity: O(m*n)

Space Complexity: O(1)

CATALOG
  1. 1. 463. Island Perimeter
  2. 2. Description
  3. 3. Example: