C# Solution (Island Perimeter)


  • 0
    A
     public int IslandPerimeter(int[,] grid) {
           int perimeter = 0;
                for (int i = 0; i < grid.GetLength(0); i++)
                {
                    for (int j = 0; j < grid.GetLength(1); j++)
                    {
                        if (grid[i,j] == 1)
                        {
                            int sideCount = 0;
                            if (i == 0)
                                sideCount++;
                            else
                            {
                                if (grid[i - 1, j] == 0)
                                {
                                    sideCount++;
                                }
                            }
                            if(i == grid.GetLength(0)-1)
                                sideCount++;
                            else
                            { 
                                if (grid[i + 1, j] == 0)
                                {
                                    sideCount++;
                                }
                            }
                            if (j == 0)
                                sideCount++;
                            else
                            {
                                if (grid[i, j-1] == 0)
                                {
                                    sideCount++;
                                }
                            }
                            if (j == grid.GetLength(1)-1)
                                sideCount++;
                            else
                            {
                                if (grid[i, j+1] == 0)
                                {
                                    sideCount++;
                                }
                            }
                            perimeter += sideCount;
                        }
                    }
                }
                return perimeter; 
        }
    

Log in to reply
 

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