Easy to understand O(mn) time O(1) space Java solution with explanation


  • 0
    E

    The idea is very straight forward. Every time we encounter an island cell (initial perimeter is 4), check its surroundings, curPerimeter-1 if there is another island cell around it.

    public class Solution {
        public int islandPerimeter(int[][] grid) {
            int res = 0;
            int n = grid.length;
            int m = grid[0].length;
            
            for(int i = 0;i<n;i++){
                for(int j = 0;j<m;j++){
                    if(grid[i][j]!=0){
                        int curPerimeter = 4;
                        curPerimeter -= i-1>=0?(grid[i-1][j]==1?1:0):0;
                        curPerimeter -= j-1>=0?(grid[i][j-1]==1?1:0):0;
                        curPerimeter -= i+1<n?(grid[i+1][j]==1?1:0):0;
                        curPerimeter -= j+1<m?(grid[i][j+1]==1?1:0):0;
                        res += curPerimeter;
                    }
                }
            }
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.