463. 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.
题目大意:(Google翻译)
您将获得一个二维整数网格形式的地图,其中1表示土地,0表示水。 网格单元水平/垂直(不是对角线)连接。 网格完全被水包围,并且恰好有一个岛(即,一个或多个连接的陆地单元)。 岛上没有“湖泊”(里面的水是不连接到岛周围的水)。 一个单元格是边长为1的正方形。网格是矩形,宽度和高度不超过100.确定岛的周长。
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
代码如下:
C++
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int Vertical_length = grid.size();//垂直长度 行数
int Horizontal_length = grid[0].size();//水平长度 列数
int island = 0;//正方形个数
int repeat = 0;//两个正方形间重复的边数
int perimeter = 0;//总边长
for(int i=0;i<Vertical_length;i++)
{
for(int j=0;j<Horizontal_length;j++)
{
if(!grid[i][j])//元素为0 跳出循环
continue;
island++;//计算正方形个数
if(i!=0 && grid[i-1][j])
//非第一行元素 && grid[i-1][j]和grid[i][j]均为1
repeat++;//重复的边数+1
if(j!=0 && grid[i][j-1])
//非第一列元素 && grid[i][j-1]和grid[i][j]均为1
repeat++;
}
}
perimeter = 4 * island - 2 * repeat;//计算总边长
return perimeter;
}
};
注意:
if(i!=0 && grid[i-1][j])
//非第一行元素 && grid[i-1][j]和grid[i][j]均为1
repeat++;//重复的边数+1
if(j!=0 && grid[i][j-1])
//非第一列元素 && grid[i][j-1]和grid[i][j]均为1
repeat++;
行元素之间比较时,从第二个元素开始于之前元素比
列元素之间比较时,从第二个元素开始于之前元素比
i和j不要搞混,(我犯过这种错误)
重复边是两条边的长度!!!!!算总周长时 repeat*2