class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int h = grid.size();
int w = grid[0].size();
int ans = 0;
int dir[4][2]={
0,1,
1,0,
-1,0,
0,-1
};
for(int i = 0;i < h; i++){
for(int j = 0;j < w; j++){
if(grid[i][j] == 1){
ans += 4;
for(int k = 0;k < 4; k++){
int x = i+dir[k][0];
int y = j+dir[k][1];
if(x < 0 || y < 0 || x >= h || y >= w)
continue;
if(grid[x][y] == 1)
ans--;
}
}
}
}
return ans;
}
};