Sponsored
Sponsored
This approach involves iterating over every cell in the grid. For each land cell (grid[i][j] == 1), we assume it initially contributes 4 to the perimeter. We then check its neighboring cells (up, down, left, right). If a neighboring cell is also land, we reduce the perimeter by one for each connection to another land cell, since that edge does not contribute to the perimeter.
Time Complexity: O(n*m) where n is the number of rows and m is the number of columns in the grid.
Space Complexity: O(1) as we only use a constant amount of extra space.
1#include <vector>
2using namespace std;
3
4class Solution {
5public:
6 int islandPerimeter(vector<vector<int>>& grid) {
7 int perimeter = 0;
8 int rows = grid.size();
9 int cols = grid[0].size();
10 for (int i = 0; i < rows; ++i) {
11 for (int j = 0; j < cols; ++j) {
12 if (grid[i][j] == 1) {
13 perimeter += 4;
14 if (i > 0 && grid[i-1][j] == 1) perimeter--;
15 if (i < rows - 1 && grid[i+1][j] == 1) perimeter--;
16 if (j > 0 && grid[i][j-1] == 1) perimeter--;
17 if (j < cols - 1 && grid[i][j+1] == 1) perimeter--;
18 }
19 }
20 }
21 return perimeter;
22 }
23};
This C++ solution uses a class with a member function to calculate the perimeter by evaluating each cell for connections to adjacent land cells.
This approach leverages Depth-First Search to traverse the land cells. Starting from any land cell, we recursively visit all connected land cells and calculate the perimeter contribution for each by checking the edges. If an edge points to water or out of bounds, it contributes to the perimeter.
Time Complexity: O(n*m), each cell is visited once.
Space Complexity: O(n*m) for the recursion stack.
1 private int Dfs(int[][] grid, int i, int j) {
if (i < 0 || j < 0 || i >= grid.Length || j >= grid[0].Length || grid[i][j] == 0) return 1;
if (grid[i][j] == -1) return 0;
grid[i][j] = -1;
return Dfs(grid, i-1, j) + Dfs(grid, i+1, j) +
Dfs(grid, i, j-1) + Dfs(grid, i, j+1);
}
public int IslandPerimeter(int[][] grid) {
for (int i = 0; i < grid.Length; i++) {
for (int j = 0; j < grid[i].Length; j++) {
if (grid[i][j] == 1) {
return Dfs(grid, i, j);
}
}
}
return 0;
}
}
This C# method implements DFS to traverse the grid and calculate the perimeter by handling land and water edge conditions.