首页 > 其他 > 详细

463.算孤岛的边长 IslandPerimeter

时间:2017-01-10 23:30:37      阅读:301      评论:0      收藏:0      [点我收藏+]

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:
技术分享


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


  1. static public int IslandPerimeter(int[,] grid) {
  2. int num = 0;
  3. int rowNum = grid.GetLength(0) - 1;
  4. int colNum = grid.GetLength(1) - 1;
  5. for (int row = 0; row <= rowNum; row++) {
  6. for (int col = 0; col <= colNum; col++) {
  7. if (grid[row, col] != 1) continue;
  8. if (row == 0) {
  9. num++;
  10. }
  11. if (row == rowNum) {
  12. num++;
  13. }
  14. if (col == 0) {
  15. num++;
  16. }
  17. if (col == colNum) {
  18. num++;
  19. }
  20. if (col - 1 >= 0 && grid[row, col - 1] == 0) {
  21. num++;
  22. }
  23. if (col + 1 <= colNum && grid[row, col + 1] == 0) {
  24. num++;
  25. }
  26. if (row - 1 >= 0 && grid[row - 1, col] == 0) {
  27. num++;
  28. }
  29. if (row + 1 <= rowNum && grid[row + 1, col] == 0) {
  30. num++;
  31. }
  32. }
  33. }
  34. return num;
  35. }





463.算孤岛的边长 IslandPerimeter

原文:http://www.cnblogs.com/xiejunzhao/p/0f335555ce85efdf3c761d7e743db189.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!