力扣200. 岛屿数量(DFS/BFS/并查集)

DFS解法:
1 class Solution { 2 public: 3 typedef pair<int,int> pii; 4 int orientation[8] = {1, 0, -1, 0, 0, 1, 0, -1}; 5 int n,m; 6 vector<vector<char>> grid; 7 map<pii, bool> visited; 8 void dfs(pii start) { 9 visited[start] = true; 10 for (int i = 0; i < 4; ++i) { 11 int x = start.first + orientation[i * 2], y = start.second + orientation[i * 2 + 1]; 12 if (x >= 0 && x < n && y >= 0 && y < m) { //注意边界 13 pii temp = make_pair(x, y); 14 if (!visited[temp] && grid[x][y] == '1') { 15 dfs(temp); 16 } 17 } 18 19 } 20 } 21 int numIslands(vector<vector<char>>& grid) { 22 this -> grid = grid; 23 n = grid.size(); 24 m = grid[0].size(); 25 int result = 0; 26 for (int i = 0; i < n; ++i) { 27 for (int j = 0; j < m; ++j) { 28 pii temp = make_pair(i, j); 29 if (grid[i][j] == '1' && !visited[temp]) { 30 result ++; 31 dfs(temp); 32 } 33 } 34 } 35 return result; 36 } 37 };
并查集:
1 class Solution { 2 public: 3 typedef pair<int, int> pii; 4 map<pii, pii> parent; 5 int orientation[4] = {1, 0, 0, 1}; //已经往右和下遍历了,检查联通性时不需要判定左和上 6 pii find(pii x) { 7 if (parent[x] == x) { 8 return x; 9 } else { 10 return parent[x] = find(parent[x]); 11 } 12 } 13 void merge(pii x, pii y) { 14 pii xx = find(x), yy = find(y); 15 if (xx != yy) { 16 parent[yy] = xx; 17 } 18 } 19 int numIslands(vector<vector<char>>& grid) { 20 int result = 0; 21 for (int i = 0; i < grid.size(); ++i) { 22 for (int j = 0; j < grid[0].size(); ++j) { 23 if (grid[i][j] == '1') { 24 parent[make_pair(i, j)] = make_pair(i, j); 25 } 26 } 27 } 28 for (int i = 0; i < grid.size(); ++i) { 29 for (int j = 0; j < grid[0].size(); ++j) { 30 if (grid[i][j] == '1') { 31 for (int k = 0; k < 2; ++k) { 32 int x = i + orientation[k * 2], y = j + orientation[k * 2 + 1]; 33 if (x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size()) { 34 if (grid[x][y] == '1') { 35 merge(make_pair(i, j), make_pair(x, y)); 36 } 37 } 38 } 39 } 40 } 41 } 42 for (int i = 0; i < grid.size(); ++i) { 43 for (int j = 0; j < grid[0].size(); ++j) { 44 pii temp = make_pair(i, j); 45 if (parent.count(temp) > 0 && parent[temp] == temp) { 46 result++; 47 } 48 } 49 } 50 return result; 51 } 52 };
浙公网安备 33010602011771号