[Solved] Depth first or breadth algorithm in adjacency List [closed]


You can implement adjacency list with vectors like this, it is much easier than using pointers. Check the code, it is also much easier to understand how it works.

#include <bits/stdc++.h>

using namespace std;

vector<int> edges[5];
bool visited[5];

void dfs(int x)
{
    visited[x] = true;
    for(int i=0; i < edges[x].size(); i++)
        if(!visited[edges[x][i]])
            dfs(edges[x][i]);
}

int main()
{
    for(int i=0; i < 5; i++)
        visited[i] = false;
    vector<pair<int, int> > inputEdges{{0, 1}, {1, 2}, {0, 3}, {3, 4}, {1, 4}};
    for(int i=0; i < inputEdges.size(); i++)
    {
        edges[inputEdges[i].first].push_back(inputEdges[i].second);
        edges[inputEdges[i].second].push_back(inputEdges[i].first);
    }
    dfs(0);
    return 0;
}

solved Depth first or breadth algorithm in adjacency List [closed]