Easy to understand Java solution - O(mn)


  • 0
    Y

    The idea is simple - loop through the entire grid, and add 1 to perimeter for each adjacent grid that is considered water for each "1" grid. It is slower than the top posts as the constant is 4 other than 2, but it is clearer to understand.

    public class Solution {
        // 0 mean land, 1 means water
        private int waterOrLand(int[][] grid, int x, int y) {
            int waterOrLand = 1;
            if (y >= 0 && y < grid.length && x >= 0 && x < grid[0].length) {
                waterOrLand = 1 - grid[y][x];
            }
            return waterOrLand;
        }
        
        public int islandPerimeter(int[][] grid) {
            int ans = 0;
            for (int i = 0; i < grid.length; ++i) {
                for (int j = 0; j < grid[0].length; ++j) {
                    if (grid[i][j] == 1) {
                        ans += waterOrLand(grid, j, i + 1);
                        ans += waterOrLand(grid, j, i - 1);
                        ans += waterOrLand(grid, j + 1, i);
                        ans += waterOrLand(grid, j - 1, i);
                    }
                }
            }
            return ans;
        }
    }
    

Log in to reply
 

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