Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

depth first search


const depthFirstTraversal = (root) => {
  if (root === null) return [];

  const result = [];
  const stack = [root];

  while (stack.length > 0) {
    const current = stack.pop();
    result.push(current.data);
    if (current.right) stack.push(current.right);
    if (current.left) stack.push(current.left);
  }
  return result;
};
Comment

depth first search

BFS-> uses queue
DFS-> uses stack or recursion (less code)
NOTE: same idea algo wise for both

IDEA:
1 declare the DS(if bfs-DS will be queue,if dfs-stack)
2 push the start node to DS
3 when you push you mark it as visited
4 until the DS is not empty run a loop
5 inside loop pop the DS(deque for queue or pop for stack) and save it in a new object actual
6 loop through the neighbors of actual
7 if the current neighbor n is not visited
8 then push n in DS
9 mark n as visited in the next line.
Comment

Depth First Search

// Java Depth First Search
// -----------------------

import java.util.*;

public class DepthFirstSearch {

    int V;
    ArrayList<Integer> adj[];

    DepthFirstSearch(int noofvertex) {
        V = noofvertex;
        adj = new ArrayList[noofvertex];
        for (int i = 0; i < noofvertex; i++) {
            adj[i] = new ArrayList<>();
        }
    }

    void edge(int x, int y) {
        adj[x].add(y);
    }

    void dfs(int sourcevertex) {
        boolean[] visited = new boolean[V];
        Stack<Integer> s = new Stack<Integer>();
        visited[sourcevertex] = true;
        s.push(sourcevertex);
        int node;
        while (!s.isEmpty()) {
            sourcevertex = s.peek();
            sourcevertex = s.pop();

            for (int i = 0; i < adj[sourcevertex].size(); i++) {
                node = adj[sourcevertex].get(i);
                if (!visited[node]) {
                    s.push(node);
                }
            }
            if (visited[sourcevertex] == false) {
                System.out.print(sourcevertex + " ");
                visited[sourcevertex] = true;
            }
        }
    }

    public static void main(String[] args) {
        DepthFirstSearch g = new DepthFirstSearch(6);

        g.edge(0, 1);
        g.edge(0, 2);
        g.edge(0, 5);
        g.edge(1, 0);
        g.edge(1, 2);
        g.edge(2, 0);
        g.edge(2, 1);
        g.edge(2, 3);
        g.edge(2, 4);
        g.edge(3, 2);
        g.edge(4, 2);
        g.edge(4, 5);
        g.edge(5, 0);
        g.edge(5, 4);

        g.dfs(0);
    }
}
Comment

depth first

class Node {
  constructor(data) {
    this.left = null;
    this.right = null;
    this.data = data;
  }
}

// depth first search tree traversal using recursive
//static implementation
const depthFirstTraversal = (root) => {
  if (root === null) return [];
  const leftValues = depthFirstTraversal(root.left); //[2 , 4 , 5 ]
  const rightValues = depthFirstTraversal(root.right); // [3 , 6 , 7 ]
  return [root.data, ...leftValues, ...rightValues];
};
const one = new Node(1);
const two = new Node(2);
const three = new Node(3);
const four = new Node(4);
const five = new Node(5);
const six = new Node(6);
const seven = new Node(7);

one.left = two;
one.right = three;
two.left = four;
two.right = five;
three.left = six;
three.right = seven;
// console.log(depthFirstTraversal(one)); // [1 ,2 , 4 , 5  ,3 , 6 ,7]

// depth first search tree traversal using while loop :

const depthFirstTraversal2 = (root) => {
  if (root === null) return [];

  const result = [];
  const stack = [root];

  while (stack.length > 0) {
    const current = stack.pop();
    result.push(current.data);
    if (current.right) stack.push(current.right);
    if (current.left) stack.push(current.left);
  }
  return result;
};
console.log(depthFirstTraversal2(one)); // [1 ,2 , 4 , 5  ,3 , 6 ,7]
Comment

depth first search

# Depth First Search: DFS Algorithm

# 1) Pick any node. 
# 2) If it is unvisited, mark it as visited and recur on all its 
#    adjacent (neighbours) nodes. 
# 3) Repeat until all the nodes are visited

graph= {
    'A' : ['B','C'],
    'B' : ['D', 'E'],
    'C' : ['F'],
    'D' : [],
    'E' : ['F'],
    'F' : []
    }
visited = set() # Set to keep track of visited nodes of graph.

def dfs(visited, graph, node):  #function for dfs 
    if node not in visited:
        ''' 
        We start with A
        Then B
        Then D
        Then E
        Then F
        Then C
        A -> B -> D -> E -> F -> C
        '''
        print(node)
        # added to visited to avoid visit the node twice 
        visited.add(node)
        for neighbour in graph[node]:
            ''' 
            * Neighbour of A : B and C but first visit B
            * Then neighbour of B : D and E but first visit D 
            * Then neighbour of D : doesn't have neighbour then backtrack to the neighbour
                of the previous node (B) which is E
            * Then neighbour of E : F
            * Then neighbour of F : doesn't have neighbour then backtrack to the neighbour 
                of the previous node E but doesn't have other neighbour except F which is visited
                So backtracking again to B and B also doesn't have nodes not visited 
                So backtracking again to A: C not visited YAY!
            '''
            dfs(visited, graph, neighbour)
    
print(dfs(visited, graph, 'A'))
Comment

depth first search tip

remember that you are putting the vertexes of your graph into a stack and that is what determines the order they are travelled
Comment

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;
}

Comment

PREVIOUS NEXT
Code Example
Python :: python declare 2d list 
Python :: // in python means 
Python :: how to create list in python 
Python :: python logical operators code 
Python :: python unbound variable 
Python :: looping nested dictionaries 
Python :: Python program to find second largest 
Python :: django filter values with e and operator 
Python :: pandas sort by list 
Python :: prompt python 
Python :: self object 
Python :: python function arguments 
Python :: k-means clustering 
Python :: how to install python 
Python :: python cast to int 
Python :: dijkstra algorithm 
Python :: how to convert decimal to binary 
Python :: transpose matrix python 
Python :: get center position of countries geopandas 
Python :: python list of possible paths 
Python :: python nasa api 
Python :: Python - Comment Parse String to List 
Python :: how to save xml file in python 
Python :: same line print python 
Python :: pygame download for python 3.10 
Python :: double digest fasta files 
Python :: one line test python 
Python :: how to app object pyhthon 
Python :: What is shadows built in name? 
Python :: dependency parser tags 
ADD CONTENT
Topic
Content
Source link
Name
3+5 =