leetcode reconstruct-itinerary

来源:互联网 发布:数控铣好看编程图案 编辑:程序博客网 时间:2024/06/03 07:21

题目链接

这个题目虽然是用的深度优先算法。其实并不是经典的深度优先。首先这个题的深度优先遍历有顺序。必须是字典序从小到大的。所以用了sortedMap这个数据结构。其次。深度优先遍历如果一个点已经使用过,那么这个点第二次遍历就不能再使用。不过这里是可以在使用的。所以就需要使用每个边进行标记。如果这个边已经使用那就不能在使用,所以便有了这个数据结构sortedMap

import java.util.Arrays;import java.util.Comparator;import java.util.HashMap;import java.util.LinkedList;import java.util.List;import java.util.PriorityQueue;import java.util.Set;import java.util.SortedMap;import java.util.TreeMap;public class Solution {    public static void main(String args[])    {        Solution solution=new Solution();        solution.findItinerary(new String [][]{{"MUC","LHR"},{"JFK","MUC"},{"SFO","SJC"},{"LHR","SFO"}});    }    HashMap<String, SortedMap<String,Integer>> map=new HashMap<String, SortedMap<String,Integer>>();    LinkedList<String> result=new LinkedList<String>();    int n;    public List<String> findItinerary(String[][] tickets) {        n=tickets.length;        for(int i=0;i<tickets.length;i++)        {            SortedMap<String,Integer> theGet=map.get(tickets[i][0]);            if(theGet==null)            {                theGet=new TreeMap<String,Integer>();                map.put(tickets[i][0], theGet);            }            Integer count=theGet.get(tickets[i][1]);            if(count==null)            {                theGet.put(tickets[i][1], 1);            }            else            {                theGet.put(tickets[i][1],count+1);            }        }        String current="JFK";        result.add(current);        help(current);        return result;    }    boolean help(String current)    {        if(result.size()==n+1)        {            return true;        }        SortedMap<String,Integer> theGet=map.get(current);        if(theGet!=null)        {            Set<String> keys = theGet.keySet();            for (String key : keys){                if(theGet.get(key)!=0)                {                    theGet.put(key, theGet.get(key)-1);                    result.add(key);                    if(help(key))return true;                    result.pollLast();                    theGet.put(key, theGet.get(key)+1);                }            }        }        return false;    }}
0 0