LeetCode/solutions/463. Island Perimeter.md
2019-09-13 23:08:41 +08:00

31 lines
1.2 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [463. Island Perimeter](https://leetcode.com/problems/island-perimeter/description/)
# 思路
求”小岛”的周长,题目给了一些“小岛”的限制条件,例如小岛没有“湖”、“小岛”都是由方块上下连接的等等。
我们只需要遍历一遍grid对于每个方块根据是否是边界和周围方块的情况进行合适的周长累加即可。
时间复杂度O(n)
# C++
```C++
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
int r = grid.size(), c = grid[0].size(), res = 0, x, y;
for(int i = 0; i < r; i++)
for(int j = 0; j < c; j++){
if(grid[i][j] == 0) continue;
if(i == 0) res++;
if(i == (r - 1)) res++;
if(j == 0) res++;
if(j == (c - 1)) res++;
for(int k = 0; k < 4; k++){ // 上下左右
x = i + dx[k];
y = j + dy[k];
if(!(x < 0 || x >= r || y < 0 || y >= c) && grid[x][y] == 0) res++;
}
}
return res;
}
};
```