給定軟件之間安裝的依賴關係,用一個二維數組表示,第一維表示依賴的序號,第二維表示依賴關係,好比要先裝
deps[0][0]
,才能裝deps[0][1]
。安裝時,要儘量先安裝依賴個數少的軟件。求安裝順序。linux
時間 O(1) 空間 O(1)面試
本題和Course Schedule的解法同樣,不會拓撲排序的能夠參考那篇文章。區別在於咱們拓撲排序後的訪問順序,原本咱們是用一個Queue來進行BFS,這裏爲了讓依賴少的先安裝,咱們將Queue換成PriorityQueue,並以依賴數排序。用優先隊列遍歷圖,很像是Cost based search 或者greedy,a star這種算法。注意,因爲可能出現兩個軟件有一樣依賴數的狀況,好比兩個軟件剩餘依賴都是0的時候,應該先裝哪一個呢?這個就要和麪試官討論了,能夠在軟件的數據結構中加入timestamp或者總依賴數等變量,供咱們在ProrityQueue中做爲第二個、第三個條件來比較。算法
public class InstallDependencies { public static void main(String[] args){ String[][] deps = {{"gcc", "gdb"},{"gcc", "visualstudio"},{"windows", "gcc"} , {"windows", "sublime"}, {"libc", "gcc"}, {"libc2", "gcc"}, {"unix", "cat"} , {"windows", "libc"}, {"windows", "libc2"}, {"linux", "cat"}, {"windows", "cat"} , {"solaris", "cat"}, {"macos","cat"}}; InstallDependencies id = new InstallDependencies(); id.install(deps, 7); } public void install(String[][] deps, int n){ HashMap<String, Software> map = new HashMap<String,Software>(); // 根據依賴關係建圖 for(String[] dep : deps){ Software src = map.get(dep[0]); Software dst = map.get(dep[1]); if(src == null){ src = new Software(dep[0]); } if(dst == null){ dst = new Software(dep[1]); } src.targets.add(dst); dst.deps = dst.deps + 1; map.put(dep[0], src); map.put(dep[1], dst); } // 用一個優先隊列來遍歷咱們的圖 PriorityQueue<Software> pq = new PriorityQueue<Software>(11 ,new Comparator<Software>(){ public int compare(Software s1, Software s2){ return s1.deps - s2.deps; } }); for(String name : map.keySet()){ if(map.get(name).deps == 0){ pq.offer(map.get(name)); } } while(!pq.isEmpty()){ Software curr = pq.poll(); System.out.println(curr.name); for(Software dst : curr.targets){ dst.deps = dst.deps - 1; if(dst.deps == 0){ pq.offer(dst); } } } } } class Software{ String name; int deps; ArrayList<Software> targets; public Software(String name){ this.deps = 0; this.name = name; this.targets = new ArrayList<Software>(); } }