LeetCode-Solutions-in-Cpp17

Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.


Project maintained by downdemo Hosted on GitHub Pages — Theme by mattgraham
class Solution {
 public:
  int findCircleNum(vector<vector<int>>& M) {
    if (empty(M) || empty(M[0])) {
      return 0;
    }
    vector<int> p{MakeSet(size(M))};
    for (int i = 0; i < size(M); ++i) {
      for (int j = 0; j < size(M[0]); ++j) {
        if (M[i][j] == 1) {
          Union(p, i, j);
        }
      }
    }
    int res = 0;
    for (int i = 0; i < size(p); ++i) {
      if (p[i] == i) {
        ++res;
      }
    }
    return res;
  }

 private:
  vector<int> MakeSet(int n) {
    vector<int> res(n);
    iota(begin(res), end(res), 0);
    return res;
  }

  int FindSet(vector<int>& p, int i) {
    while (p[i] != i) {
      i = p[i];
    }
    return i;
  }

  void Union(vector<int>& p, int parent, int child) {
    p[FindSet(p, child)] = p[FindSet(p, parent)];
  }
};