Easy java self explaining O(n) time O(1) space


  • 0
    P
        private int getEdgeNumber(int[][] grid, int i, int j, int r, int c) {
            int edges = 4;
            if (j + 1 < c && grid[i][j + 1] == 1) 
                --edges; // right
            if (i + 1 < r && grid[i + 1][j] == 1)
                --edges; // down
            if (i - 1  >= 0 && grid[i - 1][j] == 1)
                --edges; // up
            if (j - 1 >= 0 && grid[i][j-1] == 1)
                --edges; // left
            return edges;
        }
        
        public int islandPerimeter(int[][] grid) {
            if (grid == null) return 0;
            int r = grid.length;
            int c = grid[0].length;
            int perimeter = 0;
            for (int i = 0; i < r; i++) {
                for (int j = 0; j < c; j++)
                    if (grid[i][j] == 1) {
                        perimeter += getEdgeNumber(grid, i, j, r, c);
                    }
            }
            return perimeter;
        }
    
    

Log in to reply
 

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