Easy and Straightforward Java Solution


  • 0
    public class Solution {
        public int islandPerimeter(int[][] grid) {
            int res = 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 count = 0;
                    if (i == 0 || grid[i - 1][j] == 0) {
                        count++;
                    }
    
                    if (i == grid.length - 1 || grid[i + 1][j] == 0) {
                        count++;
                    }
    
                    if (j == 0 || grid[i][j - 1] == 0) {
                        count++;
                    }
    
                    if (j == grid[i].length - 1 || grid[i][j + 1] == 0) {
                        count++;
                    }
                    res += count;
                }
            }
            return res;
        }
    }
    

Log in to reply
 

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