2017计算机学科夏令营上机考试 C:岛屿周长

到LeetCode上找到了原题,以为要dfs,没想到是一道水题。一遍AC,没陷阱。

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:

class Solution {
public:
    int islandPerimeter(vector<vector<int>>& grid) {
        int i,j;
        int ans=0,count;
        for (i=0;i<grid.size();i++)
            for (j=0;j<grid[i].size();j++)
                if (grid[i][j]==1)
                {
                    count=0;
                    if (i==0 || grid[i-1][j]==0)   count++;
                    if (j==0 || grid[i][j-1]==0)   count++;
                    if (i+1==grid.size() || grid[i+1][j]==0) count++;
                    if (j+1==grid[i].size() || grid[i][j+1]==0) count++;
                    ans+=count;
                }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/always_ease/article/details/80419978