#include <iostream>
#include <vector>
using namespace std;


// Fungsi DFS untuk menjelajahi graf
void DFS(int node, vector<vector<int>> &adjList, vector<bool> &visited) {
    visited[node] = true;


    for (int neighbor : adjList[node]) {
        if (!visited[neighbor]) {
            DFS(neighbor, adjList, visited);
        }
    }
}


// Fungsi untuk menghitung komponen terhubung
int countConnectedComponents(vector<vector<int>> &adjList, int vertices) {
    vector<bool> visited(vertices, false);
    int connectedComponents = 0;


    for (int i = 0; i < vertices; i++) {
        if (!visited[i]) {
            // Jika node belum dikunjungi, berarti ini adalah awal komponen baru
            connectedComponents++;
            DFS(i, adjList, visited);
        }
    }


    return connectedComponents;
}


int main() {
    int vertices = 8; // Jumlah node
    vector<vector<int>> adjList(vertices);


    // Menambahkan edge ke graf (undirected graph)
    adjList[0] = {1};
    adjList[1] = {0};
    adjList[2] = {3};
    adjList[3] = {2};
    adjList[4] = {5};
    adjList[5] = {4};
    adjList[6] = {7};
    adjList[7] = {6};


    // Hitung jumlah komponen terhubung
    int result = countConnectedComponents(adjList, vertices);
    cout << "Jumlah komponen terhubung: " << result << endl;


    return 0;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: