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:<Solution>
這題原本想用 BFS 的方式去解,但實際是沒那麼複雜
想法如下
- 由上往下,由左至右開始掃描,這樣只要檢查右邊和下面,是不是還有連接的島嶼即可。因為題目有明確說,只會有一座島嶼,且中間不會有湖
- 每多一塊島嶼,邊的數目多4個,但只要它右邊或下面有連接其它島嶼,那麼邊數會減2
C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int islandPerimeter(vector<vector<int>>& grid) { | |
const int row = grid.size(); | |
const int col = grid[0].size(); | |
int cnt = 0; | |
for(int r = 0; r < row; ++r) { | |
for(int c = 0; c < col; ++c) { | |
if(grid[r][c] == 1) { | |
cnt += 4; | |
if(r + 1 < row && grid[r+1][c] == 1) { | |
cnt -= 2; | |
} | |
if(c + 1 < col && grid[r][c+1] == 1) { | |
cnt -= 2; | |
} | |
} | |
} | |
} | |
return cnt; | |
} | |
}; |
Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int islandPerimeter(int[][] grid) { | |
int cnt = 0; | |
for(int r = 0; r < grid.length; ++r) { | |
for(int c = 0; c < grid[0].length; ++c) { | |
if(grid[r][c] == 1) { | |
cnt += 4; | |
if(r + 1 < grid.length && grid[r+1][c] == 1) { | |
cnt -= 2; | |
} | |
if(c + 1 < grid[0].length && grid[r][c+1] == 1) { | |
cnt -= 2; | |
} | |
} | |
} | |
} | |
return cnt; | |
} | |
} |
沒有留言:
張貼留言