mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 463. Island Perimeter.md
This commit is contained in:
parent
621a8c08af
commit
51e518208a
30
463. Island Perimeter.md
Normal file
30
463. Island Perimeter.md
Normal file
@ -0,0 +1,30 @@
|
||||
# [463. Island Perimeter](https://leetcode.com/problems/island-perimeter/description/)
|
||||
# 思路
|
||||
求”小岛”的周长,题目给了一些“小岛”的限制条件,例如小岛没有“湖”、“小岛”都是由方块上下连接的等等。
|
||||
我们只需要遍历一遍grid,对于每个方块,根据是否是边界和周围方块的情况进行合适的周长累加即可。
|
||||
时间复杂度O(n)
|
||||
# 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;
|
||||
}
|
||||
};
|
||||
```
|
||||
Loading…
Reference in New Issue
Block a user