More

    [ALGORITHM] BREADTH FIRST SEARCH (BFS) GRAPH ALGORITHM

    Breadth First Search (BFS) is a graph traversal algorithm where we scan the nodes level by level i.e. we visit each of a node n’s adjacent nodes before searching any of n’s grand children.

    Algorithm

    void search (Node root){

      Queue queue = new Queue();

      visit(root);

      root.visited = true;

      Queue.enqueue (root);

      while (!queue.isEmpty()) {

        Node r = queue.dequeue();

        For each (Node n in r.adjacent){

          if (n.visited == false) {

            visit(n);

            n.visited = true;

            queue.enqueue(n);

          }

        }

      }

    }

    Unlike trees, Graphs nodes can have path to any other node even forming cycles. Hence, when working with Graph, we must also check if the node has been already visited to avoid infinite loops. In our BFS algorithm we check this using the visited flag. 

    Algorithm

    void search (Node root){

      Queue queue = new Queue();

      visit(root);

      root.visited = true;

      Queue.enqueue (root);

      while (!queue.isEmpty()) {

        Node r = queue.dequeue();

        For each (Node n in r.adjacent){

          if (n.visited == false) {

            visit(n);

            n.visited = true;

            queue.enqueue(n);

          }

        }

      }

    }

    Unlike trees, Graphs nodes can have path to any other node even forming cycles. Hence, when working with Graph, we must also check if the node has been already visited to avoid infinite loops. In our BFS algorithm we check this using the visited flag. 

    Recent Articles

    OAUTH – FREQUENTLY ASKED QUESTIONS FOR INTERVIEWS AND SELF EVALUATION

    Why is refresh token needed when you have access token? Access tokens are usually short-lived and refresh tokens are...

    SUMO LOGIC VIDEOS AND TUTORIALS

    Sumo Logic Basics - Part 1 of 2 (link is external) (Sep 29, 2016)Sumo Logic Basics - Part 2 of 2...

    GIT – USEFUL COMMANDS

    Discard all local changes, but save them for possible re-use later:  git stash Discarding local changes...

    DISTRIBUTED COMPUTING – RECORDED LECTURES (BITS)

    Module 1 - INTRODUCTION Recorded Lecture - 1.1 Introduction Part I – Definition

    BOOK REVIEW GUIDELINES FOR COOKBOOKS

    Whenever you add reviews for the book, please follow below rules. Write issues in an excel.Create an excel...

    Related Stories

    Leave A Reply

    Please enter your comment!
    Please enter your name here

    Stay on op - Ge the daily news in your inbox