My Java solution


  • 0
    S
    public class Solution {
        public int islandPerimeter(int[][] grid) {
            if (grid == null || grid.length == 0 || grid[0].length == 0) {
                return 0;
            }
            int rows = grid.length;
            int cols = grid[0].length;
            
            int result = 0;
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    if (grid[i][j] == 1) {
                        // Add 4 for each cell - 1 per each edge of the cell
                        // and then subtract number of neigbors present - 1 for each neighbor which contributes as an edge
                        result += (4 - neighbors(grid, rows, cols, i, j));
                    }
                }
            }
            
            return result;
        }
        
        private int neighbors(int[][] grid, int rows, int cols, int i, int j) {
            return present(grid, rows, cols, i - 1, j) + 
                   present(grid, rows, cols, i + 1, j) + 
                   present(grid, rows, cols, i, j - 1) + 
                   present(grid, rows, cols, i, j + 1);
        }
        
        private int present(int[][] grid, int rows, int cols, int i, int j) {
            // check for out of bound ...
            if (i >= rows || j >= cols || i < 0 || j < 0) {
                return 0;
            }
            
            return grid[i][j];
        }
    }
    

Log in to reply
 

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