1. 程式人生 > 其它 >1254. 統計封閉島嶼的數目(BFS)

1254. 統計封閉島嶼的數目(BFS)

1254. 統計封閉島嶼的數目

二維矩陣 grid 由 0 (土地)和 1 (水)組成。島是由最大的4個方向連通的 0 組成的群,封閉島是一個 完全 由1包圍(左、上、右、下)的島。

請返回 封閉島嶼 的數目。

示例 1:

輸入:grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
輸出:2
解釋:
灰色區域的島嶼是封閉島嶼,因為這座島嶼完全被水域包圍(即被 1 區域包圍)。

示例 2:

輸入:grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
輸出:1

示例 3:

輸入:grid = [[1,1,1,1,1,1,1],
             [1,0,0,0,0,0,1],
             [1,0,1,1,1,0,1],
             [1,0,1,0,1,0,1],
             [1,0,1,1,1,0,1],
             [1,0,0,0,0,0,1],
             [1,1,1,1,1,1,1]]
輸出:2

提示:

  • 1 <= grid.length, grid[0].length <= 100
  • 0 <= grid[i][j] <=1
 1 class Solution{
 2
public: 3 bool isInArea(int x, int y) { 4 return (x >= 0 && x < row && y >= 0 && y < col); 5 } 6 void bfs(vector<vector<int>> &grid, int x, int y) { 7 if (!isInArea(x, y) || grid[x][y] != 0) { 8 return; 9
} 10 queue<std::pair<int, int>> q; 11 q.push(make_pair(x, y)); 12 grid[x][y] = 1; 13 while (!q.empty()) { 14 int curX = q.front().first; 15 int curY = q.front().second; 16 q.pop(); 17 for (auto &direction : g_direction) { 18 int nextX = curX + direction[0]; 19 int nextY = curY + direction[1]; 20 if (isInArea(nextX, nextY) && grid[nextX][nextY] == 0) { 21 q.push(make_pair(nextX, nextY)); 22 grid[nextX][nextY] = 1; 23 } 24 } 25 } 26 } 27 int closedIsland(vector<vector<int>>& grid) { 28 row = grid.size(); 29 col = grid[0].size(); 30 // 1、將邊界及其相鄰的土地(0)修改為水(1) 31 // 左、右邊界及其相鄰土地修改為水域 32 for (int i = 0; i < row; i++) { 33 bfs(grid, i, 0); 34 bfs(grid, i, col - 1); 35 } 36 // 上、下邊界及其相鄰土地修改為水域 37 for (int j = 0; j < col; j++) { 38 bfs(grid, 0, j); 39 bfs(grid, row - 1, j); 40 } 41 // 2、BFS遍歷矩陣,以土地(0)為起點將土地重新整理為水域,找出封閉島嶼 42 int cnt = 0; 43 for (int i = 0; i < row; i++) { 44 for (int j = 0; j < col; j++) { 45 if (grid[i][j] == 0) { 46 bfs(grid, i, j); 47 cnt++; 48 } 49 } 50 } 51 return cnt; 52 } 53 private: 54 int row; 55 int col; 56 vector<vector<int>> g_direction = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; 57 };