463. 岛屿的周长

class Solution {
public:
    int dir[4][2]={1,0,-1,0,0,1,0-1};
    int round,row,col;
    void dfs(vector<vector<int>>& grid,int x,int y){  //(x,y)是陆地
        grid[x][y]=2;
        for(int i=0;i<4;++i){
            int new_x = x + dir[i][0];
            int new_y = y + dir[i][1];
            if(new_x>=row || new_x<0 || new_y>=col || new_y<0 || grid[new_x][new_y]==0)
                round+=1;
            else if(grid[new_x][new_y]==1)
                dfs(grid,new_x,new_y);       
        }
    }
    int islandPerimeter(vector<vector<int>>& grid) {
        row=grid.size(), col=grid[0].size(), round=0;
        for(int i=0;i<row;++i){
            for(int j=0;j<col;++j){
                if(grid[i][j]==1){
                    dfs(grid,i,j);
                    return round;
                }
            }
        }
        return 0;
    }
};

你可能感兴趣的:(LeetCode,算法,leetcode,职场和发展)