LeetCode Island Perimeter

LeetCode Island Perimeter 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:

在一个海上有一个岛,要求这个岛的周长。简单题,只要发现一个land cell,看看它的四周有没有海,比如上下左右,有一边有海,则总的周长加1,如果四周也都是land cell,则这个land cell不贡献周长。 完整代码如下: [cpp] class Solution { public: int islandPerimeter(vector<vector<int>>& grid) { int ans = 0; for (int i = 0; i < grid.size(); ++i) { for (int j = 0; j < grid[i].size(); ++j) { if (grid[i][j] == 1) { if (i == 0 || grid[i – 1][j] == 0)ans++; // top if (i + 1 == grid.size() || grid[i + 1][j] == 0)ans++; //bottom if (j == 0 || grid[i][j – 1] == 0)ans++; // left if (j + 1 == grid[i].size() || grid[i][j + 1] == 0)ans++; //right } } } return ans; } }; [/cpp] 本代码提交AC,用时212MS。居然有五千多个测试样例。。。]]>

1 thought on “LeetCode Island Perimeter

  1. Pingback: LeetCode Island Perimeter | nce3xin_code

Leave a Reply

Your email address will not be published. Required fields are marked *