Build Order: You are given a list of projects and a list of dependencies (which is a list of pairs of projects, where the second project is dependent on the first project). All of a project’s dependencies must be built before the project is. Find a build order that will allow the projects to be built. If there is no valid build order, return an error.
EXAMPLE
1
2
3
4
Input:
projects: a, b, c, d, e, f
dependencies: (a, d), (f, b), (b, d), (f, a), (d, c)
Output: f, e, a, b, d, c
publicclassGraph{privateMap<String,Project>projectMap=newHashMap<>();privateList<Project>nodes=newArrayList<>();publicvoidaddProject(Stringname){if(!projectMap.containsKey(name)){Projectp=newProject(name);nodes.add(p);nodes.put(name,p);}}publicvoidaddEdge(Edgeedge){Projectfrom=nodes.get(edge.from);Projectto=nodes.get(edge.to);if(from==null||to==null){thrownewRuntimeException();}from.addNeighbor(to);}publicList<Project>getNodes(){...};}publicclassProject{privateMap<String,Project>projectMap=newHashMap<>();privateList<Project>neighbors=newArrayList<>();privateStringname;privateintdeps=0;// 自己依赖多少个其他项目publicProject(Stringname){this.name=name;}publicvoidaddNeighbor(Projectp){if(!projectMap.containsKey(p.name)){projectMap.put(p.name,p);neighbors.add(p);p.incrementDeps();}}publicvoidincrementDeps(){this.deps++;}publicvoiddecrementDeps(){this.deps--;}publicList<Project>getNeighbors(){...}}publicclassEdge{privateStringfrom;privateStringto;}publicProject[]buildOrder(String[]projectNames,Edge[]edges){Graphgraph=buildGraph(projectNames);buildEdges(graph,edges);Project[]order=newProject[projects.length];intend=projectOrder(order,projects,0);intindex=0;while(index<order.length){Projectcurrent=order[index];/* We have a circular dependency since there are no remaining projects with
* zero dependencies. */if(current==null){returnnull;}for(Projectc:current.adjacents){c.decrementDeps();}end=projectOrder(order,current.adjacents,end);index++;}returnorder;}privateintprojectOrder(Project[]projectOrder,List<Project>projects,intend){for(Projectp:projects){if(p.deps==0){projectOrder[end++]=p;}}returnend;}
评论