C# solution (the code explains)


  • 0
    Y
    public class Solution {
        public int IslandPerimeter(int[,] grid) {
            int _count = 0;
            int lenR = grid.GetLength(0);
            int lenC = grid.GetLength(1);
            //loop through array
            for (var r = 0; r < lenR; r++)
            {
                for (var c = 0; c < lenC; c++)
                {
                    if (grid[r, c] == 1)
                    {
                        //check top
                        if (r == 0) { _count++; }
                        else if (grid[r - 1, c] == 0) { _count++; }
                        //check right
                        if (c == lenC - 1) { _count++; }
                        else if (grid[r, c + 1] == 0) { _count++; }
                        //check bottom
                        if (r == lenR - 1) { _count++; }
                        else if (grid[r + 1, c] == 0) { _count++; }
                        //check left                    
                        if (c == 0) { _count++; }
                        else if (grid[r, c - 1] == 0) { _count++; }
                    }
                }
            }
            return _count;
        }
    }
    

Log in to reply
 

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