easy understand java solution


  • 0
    Z

    check 4 neighbors of each island cell, if the neighbor reaches out of the grid or the neighbor is a water cell, add one border. Havn't think of the HashTable solution, welcome to discuss.

    public class Solution {
        public int[] dx = {-1, 0, 0, 1};
        public int[] dy = {0, -1, 1, 0};
        public int islandPerimeter(int[][] grid) {
            if (grid == null || grid.length == 0 || grid[0].length == 0) {
                return 0;
            }
            int m = grid.length;
            int n = grid[0].length;
            int perimeter = 0;
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (grid[i][j] == 0) {
                        continue;
                    }
                    for (int a = 0; a < 4; a++) {
                        int x = i + dx[a];
                        int y = j + dy[a];
                        if (x < 0 || x >= m 
                            || y < 0 || y >= n
                            || grid[x][y] == 0) {
                               perimeter++;
                        }
                    }
                }
            }
            return perimeter;
        }
    }
    

Log in to reply
 

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