美文网首页
463. Island Perimeter

463. Island Perimeter

作者: caisense | 来源:发表于2018-01-19 15:57 被阅读0次

    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:
    
    image

    思路:先数有几个land(棕色),不考虑重复边的话,总边数=land4.
    然而有重复边,即相邻两个land的公共边被重复计算了两次,记总的重复边为repeat,则最终结果为land
    4-repeat*2

    class Solution {
    public:
        int islandPerimeter(vector<vector<int>>& grid) {
            int count = 0; // land计数
            int repeat = 0; // 重复边计数
            int row = grid.size();
            int col = grid[0].size();
            for (int i = 0; i < row; i++) {
                for (int j = 0; j < col; j++) {
                    if (grid[i][j] == 1) {
                        count++; // land计数+1
                        // 若找到一个land,检查其右边和下方的区域是否也为land,若是,则重复边+1
                        // 注意i和j不要越界
                        if (j != row-1 && grid[i][j+1] == 1) repeat++;
                        if (i != col-1 && grid[i+1][j] == 1) repeat++;
                    }
                }
            }
            return count*4 - repeat*2;
        }
    };
    

    相关文章

      网友评论

          本文标题:463. Island Perimeter

          本文链接:https://www.haomeiwen.com/subject/qhogoxtx.html