๐ŸŒ• ๐ŸŒ• ๐ŸŒ— 332. ้‡ๆ–ฐๅฎ‰ๆŽ’่กŒ็จ‹

ๅžไฝ›็ซฅๅญ2022ๅนด6ๆœˆ9ๆ—ฅ
  • algorithm
  • backtrace
ๅฐไบŽ 1 ๅˆ†้’Ÿ

๐ŸŒ• ๐ŸŒ• ๐ŸŒ— 332. ้‡ๆ–ฐๅฎ‰ๆŽ’่กŒ็จ‹

้šพๅบฆ: ๐ŸŒ• ๐ŸŒ• ๐ŸŒ—

้—ฎ้ข˜ๆ่ฟฐ

img_28.png


่งฃๆณ•

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;
    }
}

่พ“ๅ‡บ

img_27.png

ไธŠๆฌก็ผ–่พ‘ไบŽ: 2022/10/10 ไธ‹ๅˆ8:43:48
่ดก็Œฎ่€…: liuxianzhishou