Loading

【leetcode】463. Island Perimeter

  You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 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", meaning the water inside 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.

  

class Solution {
public:
    int dir[5]={0,1,0,-1,0};
    int islandPerimeter(vector<vector<int>>& grid) {
        //这为啥是个eazy题目??
        // 确实是eazy game 但凡只要有相邻的方块 就减一
        int m=grid.size(),n=grid[0].size(),perimeter=0;
        for(int i=0;i<m;++i){
            for(int j=0;j<n;++j){
                if(grid[i][j]==0) continue;
                perimeter+=4;
                for(int s=0;s<4;++s){
                    int in=i+dir[s],jn=j+dir[s+1];
                    if(in>=0 && in<m && jn>=0 && jn<n && grid[in][jn]==1) perimeter-=1;//周围有联通这减去这一边
                    
                }
            }
        }
        return perimeter;
        
    }
};

 

  

posted @ 2021-11-20 14:56  aalanwyr  阅读(19)  评论(0编辑  收藏  举报