Leetcode 463. Island Perimeter
We are given a 2D grid, grid
, which is a representation of a map where:
grid[i][j] = 1
represents land.grid[i][j] = 0
represents water.Grid cells are connected horizontally or vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn’t have “lakes,” meaning the water inside the island doesn’t connect to the water outside the island.
We need to return the perimeter of the island.
To calculate the perimeter, we can iterate through each cell in the grid:
grid[i][j] == 1
), we assume it contributes 4 to the perimeter.grid[i][j+1] == 1
) and one on the bottom (grid[i+1][j] == 1
), subtract 1 from the perimeter for each pair since their borders overlap and don’t contribute to the outer perimeter.Steps:
perimeter
to 0.#include <vector>
class Solution {
public:
int islandPerimeter(std::vector<std::vector<int>>& grid) {
int rows = grid.size();
int cols = grid[0].size();
int perimeter = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] == 1) {
// Assume all four sides contribute to the perimeter initially
perimeter += 4;
// Check the cell to the right
if (j < cols - 1 && grid[i][j + 1] == 1) {
// Subtract 2 since both cells contribute only 1 total to perimeter between them
perimeter -= 2;
}
// Check the cell below
if (i < rows - 1 && grid[i + 1][j] == 1) {
// Subtract 2 for the same reason
perimeter -= 2;
}
}
}
}
return perimeter;
}
};
The time complexity of this solution is O(n*m)
, where n
is the number of rows and m
is the number of columns in the grid. Each cell is visited once, making this approach efficient for the problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?