地址 https://leetcode-cn.com/contest/weekly-contest-162/problems/number-of-closed-islands/ide
有一個二維矩陣 grid
,每一個位置要麼是陸地(記號爲 0
)要麼是水域(記號爲 1
)。spa
咱們從一塊陸地出發,每次能夠往上下左右 4 個方向相鄰區域走,能走到的全部陸地區域,咱們將其稱爲一座「島嶼」。code
若是一座島嶼 徹底 由水域包圍,即陸地邊緣上下左右全部相鄰區域都是水域,那麼咱們將其稱爲 「封閉島嶼」。blog
請返回封閉島嶼的數目。leetcode
示例1get
輸入: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 區域包圍)。it
示例2io
輸入:grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
輸出:1event
示例3class
輸入: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
題解 基本都是使用DFS 查找是否與邊界的0有所連通
這裏提供另外一種思路 並查集
檢測全部標記爲陸地的0 進行歸併 而後將與邊界連通的陸地集合刪除 最後留下的就是封閉島嶼
代碼
1 class Solution { 2 public: 3 4 int MAX_NUM; 5 vector<vector<int>> field; 6 vector<int> fa; 7 vector<int> addx; 8 vector<int> addy; 9 void init(int n) 10 { 11 for (int i = 0; i <= n; i++) 12 fa[i] = i; 13 } 14 int get(int x) 15 { 16 return fa[x] == x ? x : fa[x] = get(fa[x]);//路徑壓縮,防止鏈式結構 17 } 18 void merge(int x, int y) 19 { 20 fa[get(x)] = get(y); 21 } 22 //================================================ 23 void check(int x, int y, vector<vector<int>>& grid) 24 { 25 for (int i = 0; i < 4; i++) { 26 int newx = x + addx[i]; 27 int newy = y + addy[i]; 28 29 if (newx >= 0 && newx < grid.size() && newy >= 0 && newy < grid[0].size() 30 && grid[newx][newy] == 0) 31 { 32 int idx = x * grid[0].size() + y; 33 int anotherIdx = newx * grid[0].size() + newy; 34 merge(idx, anotherIdx); 35 } 36 } 37 } 38 39 int closedIsland(vector<vector<int>>& grid) { 40 MAX_NUM = 110; 41 field = vector<vector<int>>(MAX_NUM, vector<int>(MAX_NUM)); 42 fa = vector<int>(MAX_NUM*MAX_NUM + 1); 43 init(MAX_NUM*MAX_NUM); 44 addx = vector<int>{ 1,-1,0,0 }; 45 addy = vector<int>{ 0,0,-1,1 }; 46 for (int i = 0; i < grid.size(); i++) { 47 for (int j = 0; j < grid[0].size(); j++) { 48 if (grid[i][j] == 0) { 49 check(i, j, grid); 50 } 51 } 52 } 53 54 set<int> s; 55 56 for (int i = 0; i < grid.size(); i++) { 57 for (int j = 0; j < grid[0].size(); j++) { 58 if (grid[i][j] == 0) { 59 int idx = i * grid[0].size() + j; 60 s.insert(get(idx)); 61 } 62 } 63 } 64 65 //從統計的並查集 刪除與邊沿有關的陸地 66 for (int i = 0; i < grid.size(); i++) { 67 for (int j = 0; j < grid[0].size(); j++) { 68 if (grid[i][j] == 0 && (i == 0 || i == grid.size() - 1 || j == 0 || j == grid[0].size() - 1)) { 69 int idx = i * grid[0].size() + j; 70 s.erase(get(idx)); 71 } 72 } 73 } 74 75 return s.size(); 76 } 77 78 };