Simple Perimeter on the fly - C# O(M+N) Time O(1) Space Works for Multiple Islands !


  • 0
    C

    public int IslandPerimeter(int[,] grid) {

        var perimeter = 0;
        
        for (int row = 0; row <= grid.GetUpperBound(0); row++)
            for(int col = 0; col <= grid.GetUpperBound(1); col++)
            {
                if (grid[row, col] == 1)
                {
                    // check left
                    if (row - 1 < 0 || grid[row - 1, col] == 0) 
                    {
                        perimeter++;
                    }
                    
                    // check right
                    if (row + 1 > grid.GetUpperBound(0) || grid[row + 1, col] == 0)
                    {
                        perimeter++;
                    }
                    
                    // check top 
                    if (col - 1 < 0 || grid[row, col - 1] == 0) 
                    {
                        perimeter++;
                    }
                    
                    // check bottom 
                    if (col + 1 > grid.GetUpperBound(1) || grid[row, col + 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.