easy to understand java solution


  • 0
    L
        public int islandPerimeter(int[][] grid) {
            int row = grid.length;
            int clm = grid[0].length;
            Map<Integer, Integer> table = new HashMap<Integer, Integer>();
            int sum = 0;
            for (int i = 0; i < row; i++) {
                for (int j = 0; j < clm; j++) {
                    if (grid[i][j] == 1) {
                        sum += 4;
                        if (table.containsKey(Math.max(0, i - 1) * clm + j)) {
                            sum -= 2;
                        }
                        if (table.containsKey(Math.min(row - 1, i + 1) * clm + j)) {
                            sum -= 2;
                        }
                        if (table.containsKey(i * clm + Math.max(0, j - 1))) {
                            sum -= 2;
                        }
                        if (table.containsKey(i * clm + Math.min(clm - 1, j + 1))) {
                            sum -= 2;
                        }
                        table.put(i * clm + j, 1);
                    }
                }
            }
            return sum;
        }

Log in to reply
 

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