Java O(mn) O(1) Accepted.


  • 1
    A
    public class Solution {
        public int islandPerimeter(int[][] grid) {
            if ( (grid == null) || (grid.length==0) || (grid[0].length==0) ) {
                return 0;
            }
            
            int sides = 0;
            
            for (int i=0;i<grid.length;i++) {
                for (int j=0;j<grid[i].length;j++) {
                    if (grid[i][j] == 1) {
                        sides += getSide(grid, i-1, j);
                        sides += getSide(grid, i+1, j);
                        sides += getSide(grid, i, j-1);
                        sides += getSide(grid, i, j+1);
                    }
                }
            }
            
            return sides;
        }
        
        private int getSide(int[][] grid, int i, int j) {
            if ( (i<0) || (j<0) || (i>=grid.length) || (j>=grid[i].length) || (grid[i][j]==0) ) {
                return 1;
            }
            
            return 0;
        }
    }
    

Log in to reply
 

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