classSolution { public: int m, n; intnumIslands(vector<vector<char>>& grid){ m = grid.size(), n = grid[0].size(); vector<vector<bool>> visited(m, vector<bool>(n, false)); int count = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (!visited[i][j] && grid[i][j] == '1') { count++; bfs(grid, visited, i, j); } } } return count; }
voidbfs(vector<vector<char>>& grid, vector<vector<bool>>& visited, int i, int j){ queue<pair<int, int>> q; q.push({i, j}); visited[i][j] = true; int dx[4] = {0, 0, 1, -1}; int dy[4] = {1, -1, 0, 0}; while (!q.empty()) { auto cur=q.front(); q.pop(); int x=cur.first,y=cur.second; for(int k=0;k<4;k++){ int newX=x+dx[k]; int newY=y+dy[k]; if(newX>=0&&newX<m&&newY>=0&&newY<n&&!visited[newX][newY]&&grid[newX][newY]=='1'){ q.push({newX,newY}); visited[newX][newY]=true; } } } } };
// 并查集初始化 voidinit(){ for (int i = 0; i < n; ++i) { father[i] = i; } } // 并查集里寻根的过程 intfind(int u){ return u == father[u] ? u : father[u] = find(father[u]); // 路径压缩 }
// 判断 u 和 v是否找到同一个根 boolisSame(int u, int v){ u = find(u); v = find(v); return u == v; }
// 将v->u 这条边加入并查集 voidjoin(int u, int v){ u = find(u); // 寻找u的根 v = find(v); // 寻找v的根 if (u == v) return ; // 如果发现根相同,则说明在一个集合,不用两个节点相连直接返回 father[v] = u; }