Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

depth first search

#include <bits/stdc++.h>
using namespace std;

class Graph {
public:
	map<int, bool> visited;
	map<int, list<int> > adj;
	void addEdge(int v, int w);
	void DFS(int v);
	void PrintGraph();
	
};

void Graph::addEdge(int v, int w)
{
	adj[v].push_back(w); 
}

void Graph::PrintGraph()
{
    for(auto &it:adj)
    {
        cout<<it.first<<" : ";
        for(auto i=(it.second).begin();i!=(it.second).end();i++)
        {
            cout<<*i<<" -> ";
        }
        cout<<"NULL
";
    }    
}

void Graph::DFS(int v)
{
    visited[v]=true;
    cout<<v<<" ";
    for(auto i=adj[v].begin();i!=adj[v].end();i++)
    {
        if(!visited[*i])
        {
            DFS(*i);
        }
    }
}


int main()
{
	Graph g;
	g.addEdge(0, 1);
	g.addEdge(0, 2);
	g.addEdge(1, 2);
	g.addEdge(2, 0);
	g.addEdge(2, 3);
	g.addEdge(3, 3);
	g.PrintGraph();
	g.DFS(2);
	return 0;
}

 
PREVIOUS NEXT
Tagged: #depth #search
ADD COMMENT
Topic
Name
2+3 =