One minute
Leetcode July: Island Perimeter
I’m a bit limited on time today, but it’s fair to say that today’s problem is well suited to a brief description. The problem presents with an $m * n$ grid containing a single island and asks that we return the basic perimeter. To find the perimeter, we simply iterate over the grid to find each land cell and mark each of its neighboring non-land cells as perimeter. As I’m being brief, be sure to email me if you have any questions about my solution:
int islandPerimeter(vector<vector<int>>& grid) {
if(grid.empty()) return 0;
int perimeter = 0;
for(int i=0;i<grid.size();i++) {
for(int j=0;j<grid[0].size();j++) {
if(grid[i][j]) {
perimeter += coast(grid, i, j);
}
}
}
return perimeter;
}
int coast(vector<vector<int>>& grid, int row, int col) {
static const vector<pair<int,int>> directions = {{-1,0},{1,0},{0,-1},{0,1}};
int coastline = 0;
for(auto [dx,dy] : directions) {
int dRow = row + dx;
int dCol = col + dy;
if(dRow < 0 || dRow > grid.size()-1 || dCol < 0 || dCol > grid[0].size()-1
|| grid[dRow][dCol] == 0) {
coastline++;
}
}
return coastline;
}
Read other posts