DFS and BFS on a Single Graph

Teja IllaTeja Illa
1 min read

BFS and DFS Algorithm on a single Graph

Take an Example of the below Graph

import java.util.*;

public class Main {

  public static class Graph {
    int v;
    int e;

    List<List<Integer>> arrList;

    public Graph(int v, int e) {
      this.v = v;
      this.e = e;

      arrList = new ArrayList<>();

      for(int i=0; i<v; i++) {
        arrList.add(new ArrayList<>());
      }
    }

    public void addEdge(int start, int end) {
      arrList.get(start).add(end);
    }

    public void printGraph() {
      for(int i=0; i< this.v; i++) {
        System.out.println(arrList.get(i));
      }
    }

    public void runBFS() {
      int[] visitedList = new int[v];

      PriorityQueue<Integer> pq = new PriorityQueue<>();

      visitedList[0] = 1;
      pq.add(0);


      while(!pq.isEmpty()) {
        int top = pq.poll();
        System.out.println(top);

        List<Integer> adjVer = arrList.get(top);

        for(Integer ver : adjVer) {
          if(visitedList[ver] == 0) {
            visitedList[ver] = 1;
            pq.add(ver);
          }
        }
      }
    }

    public void runDFS() {
      int[] visitedList = new int[v];

      for(int i=0; i<v; i++) {

        if(visitedList[i] == 0) {
          dfsHelper(arrList, i, visitedList);
        }

      }
    }

    public void dfsHelper(List<List<Integer>> arrList, int root, int[] visitedList) {
      System.out.println(root);
      visitedList[root] = 1;

      List<Integer> adjList = arrList.get(root);

      for(Integer ver : adjList) {
        if(visitedList[ver] == 0) {
          dfsHelper(arrList, ver, visitedList);
        }
      }
    }
  }

  public static void main(String[] args) {

    Graph g = new Graph(7, 6);

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

    g.printGraph();
    g.runDFS();
    g.runBFS();
  }
}
0
Subscribe to my newsletter

Read articles from Teja Illa directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Teja Illa
Teja Illa