Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8b38f40

Browse files
✨ reconstruct itinerary
1 parent 531004d commit 8b38f40

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

‎src/322-reconstruct-itinerary/index.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* @param {string[][]} tickets
3+
* @return {string[]}
4+
*/
5+
// HELP:
6+
var findItinerary = function (tickets) {
7+
const graph = getGraph(tickets);
8+
const ans = [];
9+
dfs(graph, 'JFK', ans);
10+
// 深度优先遍历是先进先出,所以reverse反转一下
11+
return ans.reverse();
12+
};
13+
14+
//从JFS出发,深度优先遍历
15+
function dfs(graph, cur, ans) {
16+
if (!graph.has(cur)) return;
17+
const neighbors = graph.get(cur);
18+
// 题目要求先遍历字典序小的元素
19+
while (neighbors.length) dfs(graph, neighbors.shift(), ans);
20+
// 因为深度优先遍历是先进先出,所以每次遍历出发点添加到最后,意为最先出
21+
ans.push(cur);
22+
}
23+
24+
// 先存储所有机场之间的关系,哪怕tickets中没有给某个机场提供目的地记录,也要把它的目的地置为空数组
25+
function getGraph(tickets) {
26+
const map = new Map();
27+
// 收集每一个出发点的所有目的地
28+
for (let i = 0; i < tickets.length; i++) {
29+
const from = tickets[i][0];
30+
const to = tickets[i][1];
31+
if (!map.has(from)) map.set(from, []);
32+
if (!map.has(to)) map.set(to, []);
33+
map.get(from).push(to);
34+
}
35+
for (let [key, value] of map) {
36+
// 字典顺序排序目的地数组
37+
value.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
38+
}
39+
40+
return map;
41+
}

‎src/322-reconstruct-itinerary/pro.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @param {string[][]} tickets
3+
* @return {string[]}
4+
*/
5+
var findItinerary = function (tickets) {
6+
let map = {},
7+
result = [];
8+
for (let i of tickets) {
9+
if (!map[i[0]]) {
10+
map[i[0]] = [i[1]];
11+
} else {
12+
map[i[0]].push(i[1]);
13+
}
14+
if (!map[i[1]]) {
15+
map[i[1]] = [];
16+
}
17+
}
18+
19+
getResult(map, 'JFK', result);
20+
function getResult(map, spot, result) {
21+
// console.log(map)
22+
if (!map[spot]) return;
23+
const neighbors = map[spot];
24+
neighbors.sort();
25+
while (neighbors.length > 0) {
26+
getResult(map, neighbors.shift(), result);
27+
}
28+
result.push(spot);
29+
}
30+
31+
return result.reverse();
32+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /