Straightforward solution, easy to understand


  • 0
    S
        public int islandPerimeter(int[][] grid) {
            if (grid.length == 0 || grid[0].length == 0) {
                return 0;
            }
            
            int m = grid.length;
            int n = grid[0].length;
            int[][] directions = new int[][] {{0,1}, {1,0}, {0,-1}, {-1,0}};
            int result = 0;
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    int value = grid[i][j];
                    if (value == 1) {
                        result += getCellPerimeter(grid, i, j, directions);
                    }
                }    
            }
            return result;
        }
        
        private int getCellPerimeter(int[][] grid, int x, int y, int[][] directions) {
            int perimeter = 0;
            for (int[] dir : directions) {
                int newX = x + dir[0];
                int newY = y + dir[1];
                if (newX < 0 || newY < 0 || newX >= grid.length || newY >= grid[0].length) {
                    perimeter += 1;
                }
                else if (grid[newX][newY] == 0) {
                    perimeter += 1;
                }
            }
            return perimeter;
        }
    }

Log in to reply
 

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