💻
Algorithm
  • README
  • Array
    • At Most To Equal
    • Count Inversions In An Array
    • Interleaving Placement
    • Kadane
    • Left To Right State Transition
    • Permutation
    • Quick Select
    • Sliding Window
    • Two Pointers
  • Binary Tree
    • Avl Tree
    • Binary Search Tree
    • Serialization And Deserialization
    • Traversal
  • Company
    • Facebook
  • Cpp
    • Array
    • Memset 3 F
    • Overflow
  • Data Structure
    • Binary Indexed Tree
    • Segment Tree And Binary Index Tree
    • Segment Tree
    • Stack
    • Trie
    • Union Find
  • Dynamic Programming
    • Knapsack
      • 0 1 Knapsack
      • Bounded Knapsack
      • Unbounded Knapsack
    • Bitmask Dp
    • Dp On Subsets
    • Dp On Tree
    • Dp With Sorting
    • Selective State Dp
    • Travelling Salesperson
  • Graph
    • Minimum Spanning Tree
      • Kruskal
      • Prim
    • Shortest Path
      • Bellman Ford
      • Dijkstra
      • Floyd Warshall
      • Johnson
      • Shortest Path Faster Algorithm
    • Bi Directional Breadth First Search
    • Bipartite
    • Breadth First Search
    • Component Coloring
    • Component Count
    • Depth First Search
    • Eulerian Path
    • Maximum Bipartite Matching
    • Tarjan
    • Topological Sort
    • Tree Diameter
    • Tree Ring Order Traversal
  • Greedy
    • Greedy Scheduling
    • Regret Greedy
  • Math
    • Catalan Number
    • Combinatorics
    • Factorial
    • Factorization
    • Fast Pow
    • Gcd
    • Geometry
    • Get Digits
    • Lcm
    • Median Minimizes Sum Of Absolute Deviations
    • Mode
    • Modular Multiplicative Inverse
    • Palindrome
    • Prime Number
    • Round Up
    • Sieve Of Eratosthenes
    • Stars And Bars
    • Sum Of Sequence
  • Miscellaneous
    • Bin Packing
    • Floyds Tortoise And Hare
    • Hungarian
    • Palindrome
  • Sort
    • Bubble Sort
    • Cycle Sort
    • Heap Sort
    • Merge Sort
    • Quick Sort
    • Sorting
  • Stl
    • Cpp Stl
    • Istringstream
    • Lower Bound Upper Bound
    • Priority Queue
  • String
    • Kmp
    • Manacher
    • Rabin Karp
    • String Processing
    • Z
  • Backtracking
  • Binary Answer
  • Binary Lifting
  • Binary Search
  • Bit Manipulation
  • Date
  • Difference Array
  • Discretization
  • Divide And Conquer
  • Gray Code
  • Great Problems For Practice
  • Interval Scheduling Maximization
  • Io Optimization
  • K Subset Partitioning
  • Line Sweep
  • Longest Common Subsequence
  • Longest Increasing Subsequence
  • Meet In The Middle
  • Minmax
  • Mono Deque
  • Monotonic Stack
  • Offline Query
  • P And Np
  • Prefix State Map
  • Prefix Sum
  • Random
  • Reservoir Sampling
  • Reverse Polish Notation
  • Sqrt Decomposition
Powered by GitBook
On this page
  • Implementation
  • DFS
  • BFS
  • Union Find
  • Problems

Was this helpful?

  1. Graph

Component Count

A [component](https://en.wikipedia.org/wiki/Component_(graph_theory)) in a graph is a set of vertices where each of them are neighbors and none of them is neighbor of vertices outside of this set.

Count connected components in a graph.

Implementation

323. Number of Connected Components in an Undirected Graph (Medium)

Implement a function int getComponentCount(vector<vector<int>> &G), where G is an adjacency list representation of the graph, and the return value is the count of components in the graph.

DFS

void bfs(vector<vector<int>> &G, vector<bool> &visited, int start) {
    visited[start] = true;
    queue<int> q;
    q.push(start);
    while (q.size()) {
        int u = q.front();
        q.pop();
        for (int v : G[u]) {
            if (visited[v]) continue;
            visited[v] = true;
            q.push(v);
        }
    }
}
int getComponentCount(vector<vector<int>> &G) {
    int ans = 0;
    vector<bool> visited(G.size());
    for (int i = 0; i < G.size(); ++i) {
        if (visited[i]) continue;
        ++ans;
        bfs(G, visited, i);
    }
    return ans;
}

BFS

void bfs(vector<vector<int>> &G, vector<bool> &visited, int start) {
    visited[start] = true;
    queue<int> q;
    q.push(start);
    while (q.size()) {
        int u = q.front();
        q.pop();
        for (int v : G[u]) {
            if (visited[v]) continue;
            visited[v] = true;
            q.push(v);
        }
    }
}
int getComponentCount(vector<vector<int>> &G) {
    int ans = 0;
    vector<bool> visited(G.size());
    for (int i = 0; i < G.size(); ++i) {
        if (visited[i]) continue;
        ++ans;
        bfs(G, visited, i);
    }
    return ans;
}

Union Find

class UnionFind {
    vector<int> id, rank;
    int cnt;
public:
    UnionFind(int n) : cnt(n), id(n), rank(n, 1) {
        for (int i = 0; i < n; ++i) id[i] = i;
    }
    int find(int a) {
        return id[a] == a ? a : (id[a] = find(id[a]));
    }
    void connect(int a, int b) {
        int x = find(a), y = find(b);
        if (x == y) return;
        if (rank[x] <= rank[y]) {
            id[x] = y;
            if (rank[x] == rank[y]) rank[y]++;
        } else id[y] = x;
        --cnt;
    }
    int getCount() { return cnt; }
};
int getComponentCount(vector<vector<int>> &G) {
    UnionFind uf(G.size());
    for (int u = 0; u < G.size(); ++u) {
        for (int v : G[u]) uf.connect(u, v);
    }
    return uf.getCount();
}

Problems

  • 947. Most Stones Removed with Same Row or Column (Medium)

  • 200. Number of Islands (Medium)

  • 323. Number of Connected Components in an Undirected Graph (Medium)

PreviousComponent ColoringNextDepth First Search

Last updated 4 years ago

Was this helpful?