29 Jun 2014

Word Chain

Problem Statement:
               Count the number of minimum jumps required  from the starting word to ending word by changing only one character at each jump.

Start word:  cat    
End word: bay
Dictionary: rat , mat , ray , may , bal , ram , lay

Transition: cat - > mat - > may - > bay
Therefore hops = 3


Solution:

For the given problem we need to find the minimum hops required to reach the end word, the problem is very similar to searching for a node in a tree from the root , and at each level words differ from previous level by 1 character. For such problem we would require BFS (Breadth First Search) .

We start with the root and search for the next word by changing one character and which is also available in the dictionary. This process is repeated until end word is found and hop count is returned, if the word is not reachable by 1 character change then -1 is returned.

Below is the dictionary initialization.

private static Set dict = new HashSet();

 private static void init() 
 {
  dict.add("rat");
  dict.add("mat");
  dict.add("ray");
  dict.add("may");
  dict.add("bal");
  dict.add("ram");
  dict.add("lay");
 }


Now the sub-routine to calculate to the hop count.

/**
  * Word Chain Sub-routine, using BFS
  * @param src: start word
  * @param dst: end word
  * @return : number of hops
  */
 public static int wordChain(String src, String dst)
 {
  int level = 0;

  Queue queue = new LinkedList();
  queue.add(src);
  //used as level separator
  queue.add(null);

  while (!queue.isEmpty()) 
  {
   String popedItem = queue.poll();

   //if null found , then all elements at current level are processed
   if (popedItem == null) 
   {
    queue.offer(null);
    level++;
    continue;
   }

   //Destination word found
   if (popedItem.equalsIgnoreCase(dst))
    return level;

   //Change each character of word from 'a' to 'z', if found in dictionary add to queue, 
   // and remove from dictionary
   int i = 0;
   while (i < popedItem.length()) 
   {
    StringBuilder temp = new StringBuilder(popedItem);
    for (char j = 'a'; j <= 'z'; j++) 
    {
     temp.setCharAt(i, j);

     if (temp.toString().equalsIgnoreCase(dst))
      return level;

     if (dict.contains(temp.toString())) 
     {
      queue.add(temp.toString());
      dict.remove(temp.toString());
     }

    }
    i++;
   }
  }
  return -1;
 }
Please comment and suggestions.
Happy Coding !! :)

12 comments:

  1. Smaller exhibits, including tables, kiosks and several portable and modular inline displays, are good for companies that have to have a high-quality exhibit with
    consistent brand presentation at budget-friendly prices.
    Step 2- Identify your audience: their age group, gender, profession etc.

    This is because of a number of elements which feature
    strongly over these LED signs.

    Visit my web site - buy popup trade show display

    ReplyDelete
  2. With just a little browsing, you will find it's easy to locate wire mesh displays that can work well with your distinct
    POP location in addition to hold the items you need to show.

    There could be instances where you can use spotlighting to focus on your product.
    Luckily, new lead retrieval technology can address most of these problems.


    Have a look at my webpage: trade show display store ()

    ReplyDelete
  3. From small, mom and pop shops each of the way through to heavily established market
    leaders, every year businesses in every single industry and of
    every size choose to participate over these important promotional
    events. If your unit isn't modular, contact the corporation before
    you make any structural changes. Wood displays are used by most retail
    merchandisers because of their business because wood is often a stable and reliable material to show off products.


    My webpage :: fabric trade show displays

    ReplyDelete
  4. Hello would you mind sharing which blog platform you're using?

    I'm planning to start my own blog soon but I'm having a difficult
    time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your layout seems different
    then most blogs and I'm looking for something unique.
    P.S Sorry for getting off-topic but I had to ask!

    my webpage; keyword research

    ReplyDelete
  5. Hi, Neat post.There iis a problem together with your web site in web
    explorer, could check this? IE still is the marketplace
    leader and a large component to other people will leave out
    your excellent writing due to this problem.

    My weblog; Las Vegas Kitchen Appliance Repairman

    ReplyDelete
  6. Oh my goodness! Impressive article dude!

    Thanks, However I am encountering problems with your RSS.
    I don't understand why I can't subscribe to it. Is there anyone else getting similar
    RSS problems? Anyone who knows the answer can you kindly respond?
    Thanks!!

    My blog post social media atlanta

    ReplyDelete
  7. I every time spent my half an hour to read this website's
    content everyday along with a cup of coffee.


    Feel free to visit my web blog; marketing success

    ReplyDelete
  8. Its like you read my mind! You appear to know so much about this, like you wrote the book
    in it or something. I think that you could do with a
    few pics to drive the message home a little bit, but other than that, this is wonderful blog.
    A fantastic read. I'll certainly be back.

    Here is my site: social media marketing statistics

    ReplyDelete
  9. It's going to be ending of mine day, but before finish I am reading this impressive article to improve my knowledge.


    My webpage: medical solicitors london

    ReplyDelete
  10. Nice replies in return of this issue with genuine arguments
    and telling everything regarding that.

    Look into my website - private jet rental europe

    ReplyDelete
  11. Thank you a bunch for sharing this with all people you actually realize what you're
    talking approximately! Bookmarked. Please additionally consult with my site =).
    We could have a link exchange arrangement between us

    Feel free to surf to my blog: what to export from uk

    ReplyDelete