how to know if two vertexes are connected in graph c++

Checking if Two Vertices are Connected in a Graph in C++

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

bool isConnected(vector<vector<int>>& graph, int vertex1, int vertex2) {
    for (int neighbor : graph[vertex1]) {
        if (neighbor == vertex2) {
            return true;
        }
    }
    return false;
}

int main() {
    int numVertices = 4;
    vector<vector<int>> graph(numVertices);

    // Populate the graph (add edges)

    if (isConnected(graph, 0, 1)) {
        cout << "Vertex 0 and Vertex 1 are connected." << endl;
    } else {
        cout << "Vertex 0 and Vertex 1 are not connected." << endl;
    }

    return 0;
}

In the above C++ code snippet, we define a function called isConnected that takes a graph represented as an adjacency list and two vertices as input. It iterates through the neighbors of the first vertex and checks if the second vertex is among them. In the main function, we can use this isConnected function to check if two vertices are connected in the graph and print the result.