Clean Java Solution 129ms


  • 0
    M

    Logic:

    1. Parse the entire matrix from top to bottom.
    2. When you find 1, check whether it's surrounded by water (0), land(1), or out of bounds
      2a. If surrounded by water or when it's present in the corner, increment the perimeter
      2b. If surrounded by land, do nothing
    3. return the perimeter

    Time complexity: O(mn)
    Space Complexity: O(1)

    public int islandPerimeter(int[][] grid) {
            int perimeter = 0;
            for(int i=0; i<grid.length; i++) {
                for(int j=0; j<grid[0].length; j++) {
                    if(grid[i][j] == 1) {
                        if(i-1 < 0 || grid[i-1][j] == 0)
                            perimeter++;
                        if(j-1 < 0 || grid[i][j-1] == 0)
                            perimeter++;
                        if(j+1 >= grid[0].length || grid[i][j+1] == 0)
                            perimeter++;
                        if(i+1 >= grid.length || grid[i+1][j] == 0)
                            perimeter++;
                    }
                }
            }
            return perimeter;
        }
    

Log in to reply
 

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