Simple Java accepted solution


  • 0
    M
    public class Solution {
        public int islandPerimeter(int[][] grid) {
            if(grid == null || grid.length == 0 || grid[0].length == 0) {
                return 0;
            }
            
            int count = 0;
            for(int i = 0; i < grid.length; i++) {
                for(int j = 0; j < grid[0].length; j++) {
                    if(grid[i][j] == 0) continue;
                    int c = 0;
                    c += j-1 < 0 ? 0 : grid[i][j-1];
                    c += j + 1 >= grid[0].length ? 0 : grid[i][j+1];
                    c += i-1 < 0 ? 0 : grid[i-1][j];
                    c += i+1 >= grid.length ? 0 : grid[i+1][j];
                    count += 4 - c;
                }
            }
            return count;
        }
    }
    

Log in to reply
 

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