LeetCode-Hash-463. Island Perimeter

来源:互联网 发布:无限刷微信红包软件 编辑:程序博客网 时间:2024/06/01 10:34

问题:https://leetcode.com/problems/island-perimeter/
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:[[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]]
Answer: 16
Explanation: The perimeter is the 16 yellow stripes in the image below:
这里写图片描述

分析:
看陆地周围有没有其他的陆地,如果它左边没有陆地则贡献1,右面没有陆地贡献1个边长,下面没有陆地贡献1个边长,上面没有陆地也贡献1个边长。当然还需要考当前方块是在边上的状况。因为最左边的矩形左边是肯定没有其他陆地的。最右边的矩形右边也是没有陆地的。最上面的矩形上面没有陆地。最下面的矩形下面没有陆地。
C++代码:

class Solution {public:    int islandPerimeter(vector<vector<int>>& grid) {        int x=grid.size();        int y=grid[0].size();        int ans=0;        for(int i=0;i<x;i++){            for(int j=0;j<y;j++){                if(grid[i][j]){                    if(i==0 || grid[i-1][j]==0) ans++;                    if(i==x-1 || grid[i+1][j]==0) ans++;                    if(j==0 || grid[i][j-1]==0) ans++;                    if(j==y-1 || grid[i][j+1]==0) ans++;                }            }        }        return ans;    }};
0 0
原创粉丝点击