nikunjsoni

305

May 2nd, 2021
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. class UnionFind{
  2. public:
  3.     vector<int> parent, rank;
  4.     vector<bool> vis;
  5.     int components;
  6.    
  7.     UnionFind(int n){
  8.         parent.resize(n);
  9.         vis.assign(n, false);
  10.         for(int i=0; i<n; i++)
  11.             parent[i] = i;
  12.         rank.assign(n, 0);
  13.         components = 0;
  14.     }
  15.    
  16.     int find(int x){
  17.         return (x == parent[x]) ? x : (parent[x] = find(parent[x]));
  18.     }
  19.    
  20.     void unionSet(int x, int y){
  21.         if(!vis[x] || !vis[y]) return;
  22.         int px = find(x);
  23.         int py = find(y);
  24.         if(px != py){
  25.             components--;
  26.             if(rank[px] > rank[py]){
  27.                 parent[py] = px;
  28.             }
  29.             else{
  30.                 parent[px] = py;
  31.                 rank[py]++;
  32.             }
  33.         }
  34.     }
  35.    
  36.     void markVisited(int x){
  37.         vis[x] = true;    
  38.     }
  39. };
  40.  
  41. class Solution {
  42.    
  43. public:
  44.     vector<int> numIslands2(int m, int n, vector<vector<int>>& positions) {
  45.         UnionFind uf = UnionFind(m*n);
  46.         vector<int> ans;
  47.         for(auto edge: positions){
  48.             int x = edge[0], y = edge[1];
  49.             if(!uf.vis[x*n+y]){
  50.                 uf.components++;
  51.                 uf.markVisited(x*n+y);
  52.             }
  53.             if(x-1 >= 0){
  54.                 int  hash = (x-1)*n+y;
  55.                 uf.unionSet(x*n+y, hash);
  56.             }
  57.             if(y-1 >= 0){
  58.                 int hash = x*n + y-1;
  59.                 uf.unionSet(x*n+y, hash);
  60.             }
  61.             if(x+1 < m){
  62.                 int hash = (x+1)*n+y;
  63.                 uf.unionSet(x*n+y, hash);
  64.             }
  65.             if(y+1 < n){
  66.                 int hash = x*n + y+1;
  67.                 uf.unionSet(x*n+y, hash);
  68.             }
  69.             ans.push_back(uf.components);
  70.         }
  71.        
  72.         return ans;
  73.     }
  74. };
Advertisement
Add Comment
Please, Sign In to add comment