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:
[Thoughts]
遍历二维数组,对于每一个land点,统计边数,最后统计周长即可。
[Code]
1: int islandPerimeter(vector<vector<int>>& grid) {
2:
3: int rows = grid.size();
4: if(rows == 0) return 0;
5: int cols = grid[0].size();
6:
7: int periMeters = 0;
8: for(int i =0; i< rows; i++) {
9: for(int j =0; j< cols; j++) {
10: if(grid[i][j] == 1) {
11: periMeters += surWaters(grid, i, j);
12: }
13: }
14: }
15: return periMeters;
16: }
17:
18: int surWaters(vector<vector<int>>& grid, int x, int y) {
19: int periM = 0;
20: // x-1, y
21: if(x-1< 0) periM++;
22: else {
23: periM += (1-grid[x-1][y]);
24: }
25:
26: //x+1, y
27: if(x+1 > grid.size() -1) periM++;
28: else periM += (1-grid[x+1][y]);
29:
30: // x, y-1
31: if(y-1 < 0) periM++;
32: else periM += (1-grid[x][y-1]);
33:
34: // x, y+1
35: if(y+1 > grid[0].size() -1) periM++;
36: else periM += (1-grid[x][y+1]);
37:
38: return periM;
39: }
No comments:
Post a Comment