習題地址 https://leetcode-cn.com/problems/number-of-islands/數組
給定一個由 '1'
(陸地)和 '0'
(水)組成的的二維網格,計算島嶼的數量。一個島被水包圍,而且它是經過水平方向或垂直方向上相鄰的陸地鏈接而成的。你能夠假設網格的四個邊均被水包圍。ide
示例 1:spa
輸入: 11110 11010 11000 00000 輸出: 1
示例 2:code
輸入: 11000 11000 00100 00011 輸出: 3
解法blog
廣度遍歷或者使用並查集 這裏使用並查集。注意將二維數組轉換爲一維的方法遞歸
代碼leetcode
1 class UnionFind { 2 public: 3 vector<int> father; 4 UnionFind(int num) { 5 for (int i = 0; i < num; i++) { 6 father.push_back(i); //每一個人都指向本身 7 } 8 } 9 int Find(int n) { 10 //非遞歸版本 11 /* 12 while (father[n] != n) { 13 n = father[n]; 14 } 15 return n; 16 */ 17 //遞歸 18 if (father[n] == n) 19 return n; 20 father[n] = Find(father[n]); 21 return father[n] ; 22 } 23 void Union(int a, int b) { 24 int fa = Find(a); 25 int fb = Find(b); 26 father[fb] = fa; 27 } 28 }; 29 30 31 class Solution { 32 public: 33 int directions[4][2] = {{1,0},{-1,0},{0,1},{0,-1}}; 34 int encode(int i,int j,int n){ 35 return i*n+j; 36 } 37 int numIslands(vector<vector<char>>& grid) { 38 int M = grid.size(); 39 if(M == 0) 40 return 0; 41 int N = grid[0].size(); 42 if(N == 0) 43 return 0; 44 UnionFind UF(M*N); 45 for(int i = 0;i < M;i++){ 46 for(int j =0;j < N;j++){ 47 if(grid[i][j] == '1'){ 48 for(int d =0;d < 4; d++){ 49 int di = directions[d][0]; 50 int dj = directions[d][1]; 51 if(i+di >= 0 && i+di < M && j+dj >=0&& j+dj < N && 52 grid[i+di][j+dj] == '1') 53 { 54 UF.Union(encode(i,j,N),encode(i+di,j+dj,N)); 55 } 56 } 57 } 58 } 59 } 60 61 int res = 0; 62 for(int i =0;i < M;i++){ 63 for(int j = 0; j< N;j++){ 64 if(grid[i][j] == '1'){ 65 int id = encode(i,j,N); 66 if(UF.Find(id) == id) 67 res++; 68 } 69 } 70 } 71 72 return res; 73 74 } 75 };