Naive Solution checking four sides


  • 0
    public class Solution {
        public int islandPerimeter(int[][] grid) {
            if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
            int row = grid.length, col = grid[0].length;
            int count = 0;
            for (int i = 0; i < row; i++) {
                for (int j = 0; j < col; j++) {
                    if (grid[i][j] == 1) {
                        //up
                        if (i == 0 || (i > 0 && grid[i - 1][j] == 0)) {
                            count++;
                        }
                        //down
                        if (i == row - 1 || (i < row - 1 && grid[i + 1][j] == 0)) {
                            count++;
                        }
                        //left
                        if (j == 0 || (j > 0 && grid[i][j - 1] == 0)) {
                            count++;
                        }
                        //right
                        if (j == col - 1 || (j < col - 1 && grid[i][j + 1] == 0)) {
                            count++;
                        }
                    }
                }
            }
            return count;
        }
    }
    

Log in to reply
 

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