function findRoutes(routes) {
const dictionary = {};
const indegree = {};
routes.forEach(([from, to]) => {
dictionary[from] = to;
indegree[to] = (indegree[to] || 0) + 1;
});
const initialRoute = Object.keys(dictionary).find((el) => {
return !Object.keys(indegree).includes(el);
});
const stack = [initialRoute];
function checkRoutesPos(dictionary, initialRoute) {
let thisRoute = initialRoute;
let pushElem = dictionary[thisRoute];
while (pushElem !== undefined) {
thisRoute = dictionary[thisRoute];
stack.push(pushElem);
pushElem = dictionary[thisRoute];
}
}
checkRoutesPos(dictionary, initialRoute);
return stack.join(", ");
}
const routes = [ ["USA", "BRA"], ["JPN", "PHL"], ["UAE", "JPN"], ["BRA", "UAE"] ];
// Вывод: USA,BRA,UAE,JPN,PHL
const routes = [ ["UAE", "JPN"], ["USA", "BRA"], ["JPN", "PHL"], ["BRA", "UAE"] ];
// Браузер завис
findRoute([ ["JPN", "PHL"], ["BRA", "UAE"], ["UAE", "JPN"], ["USA", "BRA"] ])
// Вывод ['JPN', 'PHL']
findRoute([ ["BRA", "UAE"], ["JPN", "PHL"], ["UAE", "JPN"], ["USA", "BRA"] ])
// Вывод ['BRA', 'UAE', 'JPN', 'PHL']