Skip to main content

Breadth First Search Implementation in Java


Breadth First Search Implementation in Java

For Graph Class Design and DFS implementation please refer to below link:-

depth-first-search-implementation-in-java


 
/*

1. Pick a vertex.
2. Get Adjacent Vertex.
3. Insert in queue ( at tail)
4. Remove vertex from queue( head)
5. Do until no vertex left in a queue.

*/ 

void searchBFS()
 {
//this is how we define queue using LinkedList
  Queue<Character> queue=new LinkedList<Character>();
  
  queue.add(vertexlist[0].label);
  
  
 
  
  while(!queue.isEmpty())
  {
  
                 //element at head (Function in main graph class please use above link)
  ArrayList adjvertex=getNeighbours(queue.peek());
  System.out.println(queue.peek());
              //element removed at head
  queue.remove();
 
        if(adjvertex!=null)
  {
  for(int i=0;i<adjvertex.size();i++)
  {
               //element added at tail  
   queue.add((Character) adjvertex.get(i));
  }
  }
  }
  
  
 }

Comments

.

Popular posts from this blog

TWO SUM -LEET CODE PROBLEM 1

   https://leetcode.com/problems/two-sum/ Given an array of integers  nums  and an integer  target , return  indices of the two numbers such that they add up to  target . You may assume that each input would have  exactly  one solution , and you may not use the  same  element twice. You can return the answer in any order.   Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1]. Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] Example 3: Input: nums = [3,3], target = 6 Output: [0,1] class Solution {     public int[] twoSum(int[] nums, int target) {              HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();                  for(int i=0;i<nums.length;i++){                      ...

Best LeetCode Lists for Interviews

Here is a list of some of the best questions asked in interviews:-  Must do 75 https://leetcode.com/list/5hkn6wze/ Must do 60  https://leetcode.com/list/5eie1aqd/ Must do medium:-  https://leetcode.com/list/5xaelz7g/ Must do Easy:-   https://leetcode.com/list/5r7rxpr1/ Graph:-  https://leetcode.com/list/x18ervrd/  Dynamic Programming:-    https://leetcode.com/list/x14z0dxr/  FaceBook interviews:- https://leetcode.com/list/xyu98pv6/  Amazon Interviews:-  https://leetcode.com/list/5hkniyf7/  Google Interviews:- https://leetcode.com/list/xyu9xfo1/ https://github.com/nazarmubeen/TopProblems/blob/master/README.md