题目: 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矩阵,grid的land(也就是1)只能水平或者垂直相交,不能对角相交,计算land的周长。 思路就是先计算所有1的周长4*element,但是有重复的边,重合的边可以看成是右边的那个1与左边的重合,下面的那个1与上面的重合,考虑这两种情况,计算多余的边数为2*dulplicate。 代码:
class Solution { public: int islandPerimeter(vector<vector<int>>& grid) { int perimeter = 0;//周长 int dulplicate = 0;//重合的边 int element = 0;//1的个数 for (unsigned int i = 0; i < grid.size(); ++i){ for (unsigned int j = 0; j < grid[i].size(); ++j){ if (grid[i][j] == 1){ element++; if (i>0 && grid[i - 1][j] == 1){//如果当前位置与左边一个位置都为1,则重合的边加1 dulplicate++; } if (j>0 && grid[i][j - 1] == 1){//如果当前位置与上面一个位置都为1,则重合的边加1 dulplicate++; } } } } perimeter = 4 * element - 2 * dulplicate;//计算最终的周长 return perimeter; } };