Checking each neighbor of an element


  • 0
    S
    public class Solution {
        public int islandPerimeter(int[][] grid) {
            int peri = 0;
            // iterate each element row by row
            for(int row = 0; row < grid.length; row++)
            {
                for(int col = 0; col < grid[0].length; col++)
                {
                    if(grid[row][col] == 1) //if you find an element with value 1
                    {
                        peri += 4;  // initially increase the perimeter by 4
                        
                        if(row != 0) //top neighbor
                        {
                            if(grid[row-1][col] == 1)
                            {
                                peri -= 1;  //remove the edge shared between them
                            }
                        }
                        
                        if(col != 0) // left neighbor
                        {
                            if(grid[row][col-1] == 1)
                            {
                                peri -= 1; //remove the edge shared between them
                            }
                        }
                        
                        if(row != grid.length -1) //bottom neighbor
                        {
                            if(grid[row+1][col] == 1)
                            {
                                peri -= 1; //remove the edge shared between them
                            }
                        }
                        
                        if(col != grid[0].length -1) //right neighbor
                        {
                            if(grid[row][col+1] == 1)
                            {
                                peri -= 1; //remove the edge shared between them
                            }
                        }
                    }
                    
                }
            }
            
            return peri;
        }
    }
    

Log in to reply
 

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