# 题目

输入:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]



# 代码

### solution1

class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
if(grid.empty()||grid[0].empty())
{
return 0;
}
int rows=grid.size();
int cols=grid[0].size();
int len=0;
for(int row=0;row<rows;row++)
{
for(int col=0;col<cols;col++)
{
if(grid[row][col]==0) continue;
len+=4;
if(row>0&&grid[row-1][col]==1) len-=2;//上面
if(col>0&&grid[row][col-1]==1) len-=2;//左边

}
}
return len;
}
};


### solution 2

class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
if(grid.empty()||grid[0].empty())
{
return 0;
}
int rows=grid.size();
int cols=grid[0].size();
int len=0;
for(int row=0;row<rows;row++)
{
for(int col=0;col<cols;col++)
{
if(grid[row][col]==0) continue;

if(row==0||grid[row-1][col]==0) len++;//上
if(col==0||grid[row][col-1]==0) len++;//左
if(row==rows-1||grid[row+1][col]==0) len++;//下，这里注意数组越界
if(col==cols-1||grid[row][col+1]==0) len++;//右
}
}
return len;
}
};

# 问题

posted @ 2019-02-19 23:10  lightmare  阅读(72)  评论(0编辑  收藏