10000 add 332 solution · AthleticCorgi/leetcode@fadca17 · GitHub
[go: up one dir, main page]

Skip to content

Commit fadca17

Browse files
committed
add 332 solution
1 parent 2fb0818 commit fadca17

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# 332. Reconstruct Itinerary
2+
3+
## #1 DFS[AC]
4+
5+
这道题目可以用深度优先遍历来搜索,首先需要记录每个机场的所有可达机场,可以通过 `Map<String, List<String>> map`来存储,需要记住的是,我们需要对所有可达机场进行排序,以保证按照序列最小的选择顺序进行选择。然后,我们从`"JFK"`这个机场开始深度搜索。
6+
7+
```java
8+
class Solution {
9+
List<String> res = new ArrayList<>();
10+
public List<String> findItinerary(String[][] tickets) {
11+
if(tickets == null || tickets.length == 0)
12+
return new ArrayList<String>();
13+
// 获得所有的邻居
14+
Map<String, List<String>> map = new HashMap<>();
15+
for(int i=0; i<tickets.length; i++){
16+
if(!map.containsKey(tickets[i][0])){
17+
List<String> te 8000 mp = new ArrayList<>();
18+
temp.add(tickets[i][1]);
19+
map.put(tickets[i][0], temp);
20+
}else{
21+
List<String> temp = map.get(tickets[i][0]);
22+
temp.add(tickets[i][1]);
23+
// 排序
24+
Collections.sort(temp);
25+
map.put(tickets[i][0], temp);
26+
}
27+
}
28+
res.add("JFK");
29+
robot(tickets, map, "JFK", 0);
30+
return res;
31+
}
32+
33+
public boolean robot(String[][] tickets, Map<String, List<String>> map,
34+
String cur,int count){
35+
if(count == tickets.length)
36+
return true;
37+
//System.out.println(cur);
38+
List<String> nexts = map.get(cur);//获得邻居
39+
//System.out.println(cur + ":" + nexts);
40+
if(nexts == null || nexts.size() == 0){
41+
return false;
42+
}
43+
for(int i=0; i<nexts.size(); i++){
44+
String next = nexts.get(i);
45+
res.add(next);
46+
nexts.remove(i);
47+
map.put(cur, nexts);
48+
if(robot(tickets, map, next, count+1))
49+
return true;
50+
res.remove(res.size()-1);
51+
nexts.add(i, next);
52+
}
53+
return false;
54+
}
55+
}
56+
```
57+

0 commit comments

Comments
 (0)
0