【LeetCode】C++ :簡單題 - 雜湊表 463. 島嶼的周長
阿新 • • 發佈:2021-02-02
難度簡單366
給定一個
row x col
的二維網格地圖grid
,其中:grid[i][j] = 1
表示陸地,grid[i][j] = 0
表示水域。網格中的格子水平和垂直方向相連(對角線方向不相連)。整個網格被水完全包圍,但其中恰好有一個島嶼(或者說,一個或多個表示陸地的格子相連組成的島嶼)。
島嶼中沒有“湖”(“湖” 指水域在島嶼內部且不和島嶼周圍的水相連)。格子是邊長為 1 的正方形。網格為長方形,且寬度和高度均不超過 100 。計算這個島嶼的周長。
示例 1:
輸入:grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]] 輸出:16 解釋:它的周長是上面圖片中的 16 個黃色的邊示例 2:
輸入:grid = [[1]] 輸出:4示例 3:
輸入:grid = [[1,0]] 輸出:4提示:
row == grid.length
col == grid[i].length
1 <= row, col <= 100
grid[i][j]
為0
或1
這題有點不知所措,看了官方題解1還是不太懂:
tx
class Solution { constexpr static int dx[4] = {0, 1, 0, -1}; constexpr static int dy[4] = {1, 0, -1, 0}; public: int islandPerimeter(vector<vector<int>>& grid) { int n = grid.size(), m = grid[0].size(); int res = 0; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(grid[i][j]){ int cnt = 0; for(int k = 0; k < 4; k++){ int tx = i + dx[k]; int ty = j + dy[k]; // tx < 0, 到左邊界; tx >= n 到右邊界 // ty < 0 到上邊界, ty >= m 到下邊界 // grid[tx][ty] == 0 相鄰格子是水域 if(tx < 0 || tx >= n || ty < 0 || ty >= m || !grid[tx][ty]){ cnt += 1; } } res += cnt; } } } return res; } };
還是不明白。。。
class Solution { public: int direction[4][2] = {0, 1, 1, 0, -1, 0, 0, -1}; int islandPerimeter(vector<vector<int>>& grid) { int res = 0; for(int i = 0; i < grid.size(); i++){ for(int j = 0; j < grid[0].size(); j++){ if(grid[i][j] == 1){ for(int k = 0; k < 4; k++){ //上下左右四個方向 int x = i + direction[k][0]; int y = j + direction[k][1]; if (x < 0 || x >= grid.size() || //i在邊界上 y < 0 || y >= grid[0].size() || //j 在邊界上 grid[x][y] == 0){ //水域 res++; } } } } } return res; } };