Simple C#


  • 0
    A
    public class Solution {
        public int IslandPerimeter(int[,] grid) 
        {
            int r = grid.GetLength(0);
            int c = grid.GetLength(1);
            int p = 0;
            
            for(int i = 0; i < r; ++i)
            {
                for(int j = 0; j < c; ++j)
                {
                    if(grid[i,j] == 1)
                    {
                        p += GetParaMeter(grid, i, j);
                    }
                }
            }
            return p;
        }
        // check up, down, left and right. If you find land increment counter
        public int GetParaMeter(int[,] grid, int i, int j)
        {
            int r = grid.GetLength(0) - 1;
            int c = grid.GetLength(1) - 1;
            int p = 0;
            
            // top, down
            if(i - 1 < 0)
            {
                p++;
            }
            else if(grid[i-1,j] == 0)
            {
                p++;
            }
            
            if( i + 1 > r)
            {
                p++;
            }
            else if(grid[i+1, j] == 0)
            {
                p++;
            }
            
            // left ,right
            if(j - 1 < 0)
            {
                p++;
            }
            else if(grid[i,j - 1] == 0)
            {
                p++;
            }
            
            if( j + 1 > c)
            {
                p++;
            }
            else if(grid[i, j+1] ==0)
            {
                p++;
            }
            return p;
        }
    }
    

Log in to reply
 

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