...

/

Solution Review: Trace the Complete Path of a Journey

Solution Review: Trace the Complete Path of a Journey

Learn a detailed analysis of the different ways to solve the "Trace the Complete Path of a Journey" challenge.

Solution: A dictionary to deduce the starting point

Press + to interact
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace chapter_9
{
class challenge_4
{
static string tracePath(Dictionary<string, string> map)
{
string result = "";
//Create a reverse Map of given map i.e if given map has (N,C) then reverse map will have (C,N) as key value pair
//Traverse original map and see if corresponding key exist in reverse Map
//If it doesn't exist then we found our starting point.
//After starting point is found, simply trace the complete path from original map.
Dictionary<string, string> reverseMap = new Dictionary<string, string>();
//To fill reverse map, iterate through the given map
foreach (string key in map.Keys)
{
// map is an instance of Dictionary<string, string>
// type key stores the key part and
// map[key] stores the value part
reverseMap[map[key]] = key;
}
//Find the starting point of the journey
string from = "";
foreach (string key in map.Keys)
{
if (!reverseMap.ContainsKey(key) )
{
from = key;
break;
}
}
//Trace complete path
string to = map[from];
while ((map.ContainsKey(to)))
{
result += from + "->" + to + " ";
from = to;
to = map[to];
}
result += from + "->" + to + " ";
return result;
}
static void Main(string[] args)
{
Dictionary<string, string> hMap = new Dictionary<string, string>();
hMap["NewYork"] = "Chicago";
hMap["Boston"] = "Texas";
hMap["Missouri"] = "NewYork";
hMap["Texas"] = "Missouri";
Console.WriteLine(tracePath(hMap));
}
}
}

The first thing you need to do is find the starting point of the journey. A reverseMap ...