Find Itinerary from a given list of tickets HashMap Java O(n)

Find Itinerary from a given list of tickets HashMap Java O(n)


The cities joining each other is given, and you have to find the initial and final  cities along with the cities between them.

The cities joining each other is :
 "Chennai", "Banglore"
 "Bombay", "Delhi"     
 "Goa", "Chennai"
 "Delhi", "Goa"

Now find the starting point of the cities joining which will present in only left side of the data given  
and then traverse the whole data from that starting point , we will get the result. 


import java.util.*;
import java.util.Scanner;
import java.util.HashMap;
import java.util.Set;
import java.util.Map.Entry;

public class Tickets
{

 int i,j,k,l;
 public static void main(String[] args) 
 {
  HashMap<String,String> ticket= new HashMap<String,String>();
  Set<Entry<String,String>> keyValueSet=ticket.entrySet();

  ticket.put("Chennai", "Banglore");
        ticket.put("Bombay", "Delhi");
        ticket.put("Goa", "Chennai");
        ticket.put("Delhi", "Goa");

        HashMap<String, String> reverse = new HashMap<String,String>();

        
        
        String initial=null;
        for(Entry<String,String> entry : keyValueSet)
        {
         reverse.put(entry.getValue(),entry.getKey());
        }  
        for(Entry<String,String> entry : keyValueSet)
        {
         if(!reverse.containsKey(entry.getKey()))
         {
          System.out.println("The starting point:"+entry.getKey());
           initial=entry.getKey();
         }
        } 

        String finalp = ticket.get(initial);

        while (finalp != null)
        {
            System.out.print(initial +  "->" + finalp + ", ");
            initial = finalp;
            finalp = ticket.get(finalp);
        } 
       

 }


}

No comments:

Post a Comment

All Repeated Words In Text File And Their Occurrences In Java

Find All Repeated Words In Text File And Their Occurrences In Java Place your file location in the argument of the FileReader. If t...