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.
思路:
每个点的边为4,相邻的两个点共享一条边,所以每次碰到连接处,边的个数减去2。我们从左上扫到右下,所以可以只考虑右边和下边的边。
题解:
int islandPerimeter(const std::vector<std::vector<int>>& grid) { const size_t M = grid.size(); const size_t N = grid[0].size(); int perimeter(0); for(size_t i = 0; i < M; ++i) { for(size_t j = 0; j < N; ++j) { if (grid[i][j]) { perimeter += 4; if (i != M - 1 && grid[i + 1][j]) perimeter -= 2; if (j != N - 1 && grid[i][j + 1]) perimeter -= 2; } } } return perimeter;}
新闻热点
疑难解答