```
int islandPerimeter(vector<vector<int>>& grid) {
if(grid.empty()) {return 0;}
int m = grid.size(), n = grid[0].size(), cnt = 0;
for(int r = 0; r != m; ++r)
for(int c = 0; c != n; ++c)
{
if(grid[r][c] == 1 && (r == 0 || grid[r-1][c] != 1)) cnt += 1; //up
if(grid[r][c] == 1 && (r == m - 1 || grid[r+1][c] != 1)) cnt += 1; //down
if(grid[r][c] == 1 && (c == 0 || grid[r][c-1] != 1)) cnt += 1; //left
if(grid[r][c] == 1 && (c == n - 1 || grid[r][c+1] != 1)) cnt += 1; //right
}
return cnt;
}
```