332. Reconstruct Itinerary (leetcode)

1. build the graph and then dfs

 -- graph <String, List<String>>,  (the value is sorted and non- duplicate)

Collections.sort(value)

2. dfs

we use bottom-up to store the path and reverse it finally. And to check if visited or not, we remove the node.

dfs(node){
   if(node == null) return;  
   visit(node);
   visitedp[node] = true;
   for(each neightbors from node){
       if(! visited neighbors) dfs(neighbors);  
    }
}

Here we use the adjacent list 

dfs(graph, curKey){
    if(!garph.containsKey(curKey) || graph.get(curKey).size()==0)
        return;  
     //visit (top down)
     while(graph.get(curKey).size()){
        String temp = graph.get(curKey).get(0);
        graph.get(curKey).remove(0); //remvoe the path
        dfs(graph, temp);
        //visit bottom up
     }
}

Solution

class Solution {
    //what is the problem of top down
    //solve this by bottom up
    List<String> res = new ArrayList<>();
    public List<String> findItinerary(String[][] tickets) {
        //build graph
        Map<String, List<String>> graph = new HashMap<>();
        for (String[] ticket : tickets) {
            if (!graph.containsKey(ticket[0])) graph.put(ticket[0], new ArrayList<>()); //contains check the null first
            graph.get(ticket[0]).add(ticket[1]);
        }
        
        //sorting the value by value
        for (String key : graph.keySet()) {
            Collections.sort(graph.get(key));
        }
        dfs("JFK",graph);
        res.add("JFK");
        Collections.reverse(res);
        
        return res;
    }
    void dfs(String cur,Map<String, List<String>> graph){
        
        if(!graph.containsKey(cur) || graph.get(cur).size() == 0) return;
        //res.add(graph.get(cur).get(0));
        
        //seach all the list
        while(graph.get(cur).size()!=0){
            String temp = graph.get(cur).get(0);//
            graph.get(cur).remove(0);
        
            dfs(temp,graph);
            res.add(temp);
        }
    }
}

how to build graph efficiently?

猜你喜欢

转载自www.cnblogs.com/stiles/p/leetcode332.html