463.算孤岛的边长 IslandPerimeter

You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.

Example:

[[0,1,0,0],
 [1,1,1,0],
 [0,1,0,0],
 [1,1,0,0]]

Answer: 16
Explanation: The perimeter is the 16 yellow stripes in the image below:[object Object]


用一个二位数组表示一个地图,1表示陆地,0表示海水,求由1组成的区域的边长。

  1. using System;
  2. using System.Collections.Generic;
  3. namespace Solution
  4. {
  5. public class Solution {
  6. public int IslandPerimeter(int[,] grid) {
  7. int res = 0;
  8. int rowNum = grid.GetLength(0);
  9. int colNum = grid.GetLength(1);
  10. if(grid == null || rowNum == 0 || colNum == 0)
  11. return res;
  12. for (int row = 0; row < rowNum; row++) {
  13. for (int col = 0; col < colNum; col++) {
  14. if(grid[row,col] == 1){
  15. res += 4;
  16. //与别的岛屿相连,总数要-2
  17. if(row > 0 && grid[row - 1, col] == 1) res -= 2;
  18. if(col > 0 && grid[row, col - 1] == 1) res -= 2;
  19. }
  20. }
  21. }
  22. return res;
  23. }
  24. }
  25. class Program
  26. {
  27. static void Main(string[] args)
  28. {
  29. var s = new Solution();
  30. int[,] arr = {{0,1,0,0},
  31. {1,1,1,0},
  32. {0,1,0,0},
  33. {1,1,0,0}};
  34. var res = s.IslandPerimeter(arr);
  35. }
  36. }
  37. }





原文地址:https://www.cnblogs.com/xiejunzhao/p/0f335555ce85efdf3c761d7e743db189.html