Skip to main content

Data Structures: Traversing a Graph

Let's say we want to find the path between an origin and a destination in a graph.  We'll want to return a LinkedList that lists vertices in order from the origin to the destination.  To do this we’ll find the shortest path.

In order to implement a getShortestPath method, we can take the following steps:

  1. Create a queue.  This will tell you the next vertices to visit.
  2. Create a map.  This will allow you to identify visited vertices, as well as trace your path backward.
  3. Add the origin vertex to your queue.
  4. Add the origin vertex to your map (try origin as the key, and null as the value).
  5. Then, while your queue is not empty (i.e. while you still have nodes not traversed):
    1. Retrieve & remove the next value from your queue.  We’ll call it “currentVertex” for now.
    2. If currentVertex is your destination, you’ve finished.  Calculate the path from origin to destination (using your map) and return it.
    3. If currentVertex is not your destination, retrieve the vertices adjacent to it.  
      1. We can call each of these neighbor vertices “neighborVertex” for now.
      2. If neighborVertex is not a key in your map, then add it to the queue.
      3. Also, if neighborVertex is not a key in your map, add it to your map (where the map keys are neighborVertex, and the map values are currentVertex).
    4. If your queue is empty, that means you’ve looked at all of the vertices. There’s no path from origin to destination, so return null.
The procedure for calculating the path from origin to destination is pretty easy once you’ve found the destination and you have a map (where the keys are vertices, and their values are how you traveled to that vertex).
  1. Create a variable called “current” and set it equal to your destination.
  2. Create a LinkedList to represent the path.
  3. While current is not your origin:
    1. Add current to the front of your list.
    2. Retrieve the value for current from the map.
    3. Set current equal to that value.
  4. Add origin to the front of your list.
Note that there may be 2 or more shortest paths from origin to destination in your graph - that’s OK and not entirely unexpected.

Consider this graph:

If we are trying to find the shortest path from A to F, we start with an empty queue and an empty map.
  • map: {}
  • queue: 
We start by adding the origin to our queue, and identify in our map that it came from "nowhere" - i.e., it's where we're starting.
  • map: {A => null}
  • queue: A
Then we start step 3.  We take A from the queue:
  • map: {A => null}
  • queue: 
  • currentVertex: A
A is not our destination, so we proceed to check the neighbors of A.  None of them are in our map, so we add them to the queue and the map:
  • map: {A => null, B => A, D => A}
  • queue: B, D
  • currentVertex: A
Now we retrieve and remove the front of our queue:
  • map: {A => null, B => A, D => A}
  • queue: D
  • currentVertex: B
B is not our destination, so we proceed to check the neighbors of B. B’s neighbors are A, C, and F.  A and B are already keys in our map, so we add F to the queue and the map:
  • map: {A => null, B => A, D => A, F => B}
  • queue: D, F
  • currentVertex: B
Now we retrieve and remove the front of our queue again:
  • map: {A => null, B => A, D => A, F => B}
  • queue: F
  • currentVertex: D
D is not our destination, so we proceed to check the neighbors of D. D’s neighbors are A and E.  A is already a key in our map, so we add E to the queue and the map:
  • map: {A => null, B => A, D => A, E => D, F => B}
  • queue: F, E
  • currentVertex: D
Now we retrieve and remove the front of our queue again:
  • map: {A => null, B => A, D => A, E => D, F => B}
  • queue: E
  • currentVertex: F
F is our destination, so we retrieve the values from a map and build a Linked List.  We start with current = F.
  • map: {A => null, B => A, D => A, E => D, F => B}
  • current: F
  • list: 
We add F to the beginning of the list, then retrieve the value of F from the map and get B and set current to B.
  • map: {A => null, B => A, D => A, E => D, F => B}
  • current: B
  • list: F
We add B to the beginning of the list, then retrieve the value of B from the map and get A.
  • map: {A => null, B => A, D => A, E => D, F => B}
  • current: A
  • list: B => F
Our destination is A, so we are done looping.  We just need to add A to the beginning of our list.  We end up with this:
  • map: {A => null, B => A, D => A, E => D, F => B}
  • current: A
  • list: A => B => F

ABF is the shortest path.

You can try this approach with any two vertices in your graph - if any path exists between them, this algorithm will find the shortest path.  If you’re not sure - try working out the algorithm on paper for origin=A and destination=G.  There are 3 possible paths from A to G; ABCFG, ABFG, and ADEHG.  This algorithm will find the shortest (ABFG).

Comments

Popular posts from this blog

The Gobbler from Arby's

Stop.  Stop what you're doing and go to Arby's. Right. Now.  Have them make you a Gobbler .  This is not something you'll regret. Go. Eat this thing. Look at that bacon. Go. Arby's has a new sandwich.  It's called "The Gobbler" and as far as I can tell it's two things: a vehicle for their new deep fried turkey, and an attempt at a Thanksgiving themed sandwich.  It's also a third thing: magically delicious. move over Lucky, there's a new holiday mascot on the block Unwrapping: this actually looks like a sandwich.  It looks appetizing.  It looks like something I want to eat.  It doesn't look like the promo photo above, but it doesn't look like someone was flailing around and accidentally smashed up a sandwich, either. sexy Instagram caption goes here First bite: Wow.  I mean, "WOW."  Holy h*ck this is good.  The turkey has a really bold, meaty flavor.  It tastes a lot like turkey sliced fresh from your...

Get Go Sandwich Standoff: "The General" vs "The Rogie Hoagie"

Get Go has been KILLING it lately with crazy sandwiches that are great for advertising on the radio but I've been wondering if they're actually great for eating. The new one I've been hearing about is "The General" which is like Chinese take-out on a sesame sub roll.  I hear ads for it every morning on my commute, and I see a giant billboard for it too.  It's basically chicken tenders with General Tso's sauce and egg rolls on a sesame bun.  I'm guessing they were inspired by Primanti's and decided to try to apply it to a different cuisine (I'm looking forward to The Russian Borscht sub which I'm sure is planned for later this summer). I ventured out to my local GetGo to try one of these out, only to be greeted by "The Rogie Hoagie" on the screen in addition to "The General."  What a great surprise (and additional gastronomic challenge)!  I decided to try them both and report back.  "The General" only comes...

Sheetz Sandwich Standoff: El Gringo vs Twisted Swiss

My wife left me alone for dinner tonight so I decided to check out the latest GetGo offerings... but to my great chagrin, they have no promotional subs. My travels led me to the local Sheetz, where I'd be able to keep eating the best gas station sandwiches around. To keep tradition alive, I picked the two most outrageous "Burgerz" on the menu: El Gringo and Twisted Swiss. The ingredient list is promising: Twisted Swiss is the burger with topped with swiss cheese, cole slaw, pickles, bacon, and whatever "Boom Boom Sauce" is on a pretzel bun.  El Gringo is the burger topped with pepper jack cheese, chili, Doritos, and BBQ sauce on a regular old bun. I unwrapped them both and stood back to admire the majesty before me. They're not pretty, but they do look a lot better out of the wrapper than many fast food burgers I've eaten. Twisted Swiss I expected this sandwich to be an awful mess.  It just seemed like a bunch ...