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:
my answer:
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int i=0;
int j=0;
if(grid.size()==0)
return 0;
for(int a=0;a<grid.size();a++)
{
for(int b=0;b<grid[0].size();b++)
{
if(!grid[a][b])
{
continue;
}
i++;
if(b!=0&&grid[a][b-1])
j++;
if(a!=0&&grid[a-1][b])
j++;
}
}
return 4*i-2*j;
}
};
本题注意事项:
1.首先求出二维数组中所有1的个数i。
2.求出遮住的边, if(b!=0&&grid[a][b-1])求出行中所盖住的边, if(a!=0&&grid[a-1][b])求出列中所盖住的边。但是这是有前提的,必须要求grid[a][b]=1; 否则就会出现错误 if(!grid[a][b]) {continue;} 此if 就是为了避免此错误。