Intuitive one

public class Solution { private final static int[][] dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; 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; } for (int[] d : dir) { int nx = i + d[0], ny = j + d[1]; if (nx < 0 || nx >= grid.length || ny < 0 || ny >= grid[0].length || grid[nx][ny] == 0) { res++; } } } } return res; } }Island Perimeter