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.
1class Solution {
2 public int islandPerimeter(int[][] grid) {
3 int perimeter = 0;
4 for (int i = 0; i < grid.length; i++) {
5 for (int j = 0; j < grid[i].length; j++) {
6 if (grid[i][j] == 1) {
7 perimeter += 4;
8 if (i > 0 && grid[i-1][j] == 1) perimeter--;
9 if (i < grid.length - 1 && grid[i+1][j] == 1) perimeter--;
10 if (j > 0 && grid[i][j-1] == 1) perimeter--;
11 if (j < grid[i].length - 1 && grid[i][j+1] == 1) perimeter--;
12 }
13 }
14 }
15 return perimeter;
16 }
17}
This Java solution iterates over each cell in the grid and calculates the perimeter by adjusting for land cell adjacency.
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
This JavaScript code uses DFS to explore the grid, marking visited cells and counting perimeter contributions via recursive depth-first traversal.