Easy Math


  • 0
    D
    public int islandPerimeter(int[][] grid) {
            if(grid.length == 0 || grid[0].length == 0) return 0;
            int ans = 0;
            for(int i = 0; i < grid.length; i++) {
                for(int j = 0; j < grid[0].length; j++) {
                    if(grid[i][j] == 1) {
                        ans += len(grid, i, j);
                    }
                }
            }
            return ans;
        }
        
        private int len(int[][] grid, int i, int j) {
            int len = 4;
            if(i > 0){
                if(grid[i-1][j] == 1) len--;
            }
            if(i < grid.length - 1) {
                if(grid[i+1][j] == 1) len--;
            }
        
            if(j > 0) {
                
                if(grid[i][j-1] == 1) len--;
                
            }
            if( j < grid[0].length - 1) {
                
                if(grid[i][j+1] == 1) len--;   
            }
            return len;
        }
    

Log in to reply
 

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