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