public class Solution {
    public int IslandPerimeter(int[,] grid) {
        var row = grid.GetLength(0);//行数
            var col = grid.GetLength(1);//列数
            var count = 0;
            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < col; j++)
                {
                    if (i == 0)
                    {
                        if (grid[i, j] == 1)
                        {
                            count++;
                        }
                    }
                    else
                    {
                        if (grid[i, j] != grid[i - 1, j])
                        {
                            count++;
                        }
                    }
                    if (i == row - 1 && grid[i, j] == 1)
                    {
                        count++;
                    }
                }
            }

            for (int j = 0; j < col; j++)
            {
                for (int i = 0; i < row; i++)
                {
                    if (j == 0)
                    {
                        if (grid[i, j] == 1)
                        {
                            count++;
                        }
                    }
                    else
                    {
                        if (grid[i, j] != grid[i, j - 1])
                        {
                            count++;
                        }
                    }

                    if (j == col - 1 && grid[i, j] == 1)
                    {
                        count++;
                    }
                }
            }
            //Console.WriteLine(count.ToString());
            return count;
    }
}

https://leetcode.com/problems/island-perimeter/#/description

posted on 2017-04-19 10:54  Sempron2800+  阅读(137)  评论(0编辑  收藏  举报