Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

Depth first search(DFS)

Algorithm

void dfs(int node, vector<int> adj[], vector<int>& vis, vector<int>& ans)
{
    vis[node] = 1;
    ans.push_back(node);
    for (auto it : adj[node]) {
        if (!vis[it]) {
            dfs(it, adj, vis, ans);
        }
    }
}
vector<int> dfsOfGraph(int N, vector<int> adj[])
{
    vector<int> ans;
    vector<int> vis(N, 0);
    int start = 0;
    dfs(start, adj, vis, ans);
    return ans;
}