1. 题目描述
2. 题目分析
- 一开始题主看到这个题,有点懵,不知道该如何下手
- 想了想,可以直接暴力,循环每一个岛【grid[]i[j] == 1】
- 然后分别判断他的四周【上下左右】是否为0,为0的话,周长加一,最后返回结果
3. 题目代码
public int IslandPerimeter(int[][] grid)
{
if(grid == null || grid.Length == 0)
{
return 0;
}
int res = 0;
for (int i = 0; i < grid.Length; i++)
{
for(int j = 0; j < grid[0].Length; j++)
{
if(grid[i][j] == 1)
{
if(i == 0 || grid[i-1][j] == 0)
{
res++;
}
if(i == grid.Length - 1 || grid[i+1][j] == 0)
{
res++;
}
if(j == 0 || grid[i][j-1] == 0)
{
res++;
}
if(j == grid[0].Length - 1 || grid[i][j+1] == 0)
{
res++;
}
}
}
}
return res;
}