Extend island solution for java


  • 0
    A
    public class Solution
    {
        public int islandPerimeter(int[][] grid)
    	{
    		int perimeter = 0;
    		
    		int[][] extendGrid = new int[grid.length+2][grid[0].length+2];
    		
    		// Extend grid with 0 around origin grid  
    		for (int i = 0; i < extendGrid.length; i++)
    		{
    			for (int j = 0; j < extendGrid[i].length; j++)
    			{
    				if( 0<i && i<extendGrid.length-1 && 0<j && j<extendGrid[i].length-1 )
    				{
    					extendGrid[i][j] = grid[i-1][j-1];
    				}
    				else
    				{
    					extendGrid[i][j] = 0;
    				}
    			}
    		}
    		
    		// Compute perimeter
    		for (int i = 0; i < extendGrid.length; i++)
    		{
    			for (int j = 0; j < extendGrid[i].length; j++)
    			{
    			    // select land
    				if ( extendGrid[i][j] == 1 )
    				{
    					if ( extendGrid[i-1][j] == 0 )
    					{
    						perimeter++;
    					}
    					if ( extendGrid[i+1][j] == 0 )
    					{
    						perimeter++;
    					}
    					if ( extendGrid[i][j-1] == 0 )
    					{
    						perimeter++;
    					}
    					if ( extendGrid[i][j+1] == 0 )
    					{
    						perimeter++;
    					}
    				}
    			}
    		}
    		return perimeter;
    	}
    }

Log in to reply
 

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