给定一个门票列表,使用给定的列表按顺序查找行程。
例子:
Input:
"Chennai" -> "Banglore"
"Bombay" -> "Delhi"
"Goa" -> "Chennai"
"Delhi" -> "Goa"
Output:
Bombay->Delhi, Delhi->Goa, Goa->Chennai, Chennai->Banglore,
可以假设输入的车票列表不是循环的,并且除了最终目的地外,每个城市都有一张车票。
一种解决方案是构建一个图并对图进行拓扑排序。该解决方案的时间复杂度为 O(n)。
我们还可以使用散列来避免构建图。这个想法是首先找到起点。起点永远不会在机票的“到”一侧。一旦我们找到起点,我们就可以简单地遍历给定的地图,按顺序打印行程。以下是步骤。
1) Create a HashMap of given pair of tickets. Let the created
HashMap be 'dataset'. Every entry of 'dataset' is of the form
"from->to" like "Chennai" -> "Banglore"
2) Find the starting point of itinerary.
a) Create a reverse HashMap. Let the reverse be 'reverseMap'
Entries of 'reverseMap' are of the form "to->form".
Following is 'reverseMap' for above example.
"Banglore"-> "Chennai"
"Delhi" -> "Bombay"
"Chennai" -> "Goa"
"Goa" -> "Delhi"
b) Traverse 'dataset'. For every key of dataset, check if it
is there in 'reverseMap'. If a key is not present, then we
found the starting point. In the above example, "Bombay" is
starting point.
3) Start from above found starting point and traverse the 'dataset'
to print itinerary.
上述所有步骤都需要 O(n) 时间,因此总时间复杂度为 O(n)。
下面是上述想法的Java实现。
Java
// Java program to print itinerary in order
import java.util.HashMap;
import java.util.Map;
public class printItinerary
{
// Driver function
public static void main(String[] args)
{
Map dataSet = new HashMap();
dataSet.put("Chennai", "Banglore");
dataSet.put("Bombay", "Delhi");
dataSet.put("Goa", "Chennai");
dataSet.put("Delhi", "Goa");
printResult(dataSet);
}
// This function populates 'result' for given input 'dataset'
private static void printResult(Map dataSet)
{
// To store reverse of given map
Map reverseMap = new HashMap();
// To fill reverse map, iterate through the given map
for (Map.Entry entry: dataSet.entrySet())
reverseMap.put(entry.getValue(), entry.getKey());
// Find the starting point of itinerary
String start = null;
for (Map.Entry entry: dataSet.entrySet())
{
if (!reverseMap.containsKey(entry.getKey()))
{
start = entry.getKey();
break;
}
}
// If we could not find a starting point, then something wrong
// with input
if (start == null)
{
System.out.println("Invalid Input");
return;
}
// Once we have starting point, we simple need to go next, next
// of next using given hash map
String to = dataSet.get(start);
while (to != null)
{
System.out.print(start + "->" + to + ", ");
start = to;
to = dataSet.get(to);
}
}
}
C++
#include
using namespace std;
void printItinerary(map dataSet)
{
// To store reverse of given map
map reversemap;
map::iterator it;
// To fill reverse map, iterate through the given map
for (it = dataSet.begin(); it!=dataSet.end(); it++)
reversemap[it->second] = it->first;
// Find the starting point of itinerary
string start;
for (it = dataSet.begin(); it!=dataSet.end(); it++)
{
if (reversemap.find(it->first) == reversemap.end())
{
start = it->first;
break;
}
}
// If we could not find a starting point, then something wrong with input
if (start.empty())
{
cout << "Invalid Input" << endl;
return;
}
// Once we have starting point, we simple need to go next,
//next of next using given hash map
it = dataSet.find(start);
while (it != dataSet.end())
{
cout << it->first << "->" << it->second << endl;
it = dataSet.find(it->second);
}
}
int main()
{
map dataSet;
dataSet["Chennai"] = "Banglore";
dataSet["Bombay"] = "Delhi";
dataSet["Goa"] = "Chennai";
dataSet["Delhi"] = "Goa";
printItinerary(dataSet);
return 0;
}
// C++ implementation is contributed by Aditya Goel
Python3
class Solution():
#Solution class carries method for printing iterary
def __init__(self):
pass
#method for printing iterary
def printIterary(self,d):
# First step : create a reversed mapping. Here also for storing key value pairs dictionary is used.
reverse_d = dict()
for i in d:
reverse_d[d[i]] = i
# Second step : find the starting point. Starting point will be that value which is not present in 'd' as key.
for i in reverse_d:
if reverse_d[i] not in reverse_d:
starting_pt = reverse_d[i]
break;
#Third step : simply proceed one by one to print whole route. Assuming that there exist Starting point.
while(starting_pt in d):
print(starting_pt,"->",d[starting_pt],end=", ")
starting_pt = d[starting_pt]
#method prints here only. Does not return anything.
if __name__=="__main__":
# Mapping using inbuilt data structure 'dictionary'
d = dict()
d["Chennai"] = "Banglore"
d["Bombay"] = "Delhi"
d["Goa"] = "Chennai"
d["Delhi"] = "Goa"
# call for method that would print Iteraty.
obj = Solution()
obj.printIterary(d)
输出
Bombay->Delhi, Delhi->Goa, Goa->Chennai, Chennai->Banglore,
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。