๐ ๐ ๐ 332. ้ๆฐๅฎๆ่ก็จ
2022ๅนด6ๆ9ๆฅ
- algorithm
๐ ๐ ๐ 332. ้ๆฐๅฎๆ่ก็จ
้พๅบฆ: ๐ ๐ ๐
้ฎ้ขๆ่ฟฐ
่งฃๆณ
class Solution {
HashMap<String, TreeMap<String, Integer>> map;
int total;
List<String> res;
public List<String> findItinerary(List<List<String>> tickets) {
// ๆ่ทฏ๏ผ
// ๅญๅ
ธๅบๆๅฐ็่ก็จ็ปๅ - ๆๅบ - TreeSet
// ๆบ็ฅจๅญๅจ้ๅค - ่ฎฐๅฝๆฌกๆฐ - TreeMap
int len = tickets.size();
total = len + 1; // ้่ฆ็ปๅ็็ซ็นๆฐ
map = new HashMap<>();
// ๅๅงๅ map
for(List<String> cur: tickets) {
String from = cur.get(0);
String to = cur.get(1);
if(!map.containsKey(from)) {
TreeMap<String, Integer> tmpMap = new TreeMap<>();
map.put(from, tmpMap);
}
TreeMap<String, Integer> tmap = map.get(from);
if(!tmap.containsKey(to)) {
tmap.put(to, 1);
} else {
int fre = tmap.get(to);
fre ++;
tmap.put(to, fre);
}
map.put(from, tmap); // ๆดๆฐ็ฅจๆฐ
}
// ๅๆบฏ
String first = "JFK";
LinkedList<String> path = new LinkedList<>();
path.addLast(first);
mySol(first, path);
return res;
}
private boolean mySol(String from, LinkedList<String> path) {
// System.out.println(Arrays.toString(path.toArray()));
// ้ๅฝ็ปๆญขๆกไปถ
if(path.size() == total) {
// ๆๆๆบ็ฅจๅทฒ็ป็จๅฎ
res = new LinkedList<String>(path);
return true;
}
// ็ปง็ปญไปๅฝๅ็ซ็นๅบๅ
TreeMap<String, Integer> tmap = map.get(from);
if(tmap == null) {
return false;
}
for(Map.Entry<String, Integer> entry: tmap.entrySet()) {
String to = entry.getKey();
int count = entry.getValue();
if(count <= 0) {
continue;
}
// System.out.println(from + " --> " + to + " " + count);
count --;
tmap.put(to, count);
map.put(from, tmap);
path.addLast(to);
if(mySol(to, path)) {
return true;
}
count ++;
// count ไธบๅบๆฌๆฐๆฎ็ฑปๅ๏ผๅ ๆญค้่ฆๆๅจๅทๅ map
tmap.put(to, count);
map.put(from, tmap);
path.removeLast();
}
return false;
}
}