There is a total of n courses you have to take, labeled from 0 to n - 1 .
Some courses May has prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a Pair[0,1]
Given the total number of courses and a list of prerequisite pairs, are it possible for your to finish all courses?
For example:
2, [[1,0]]
There is a total of 2 courses to take. To take course 1 should has finished course 0. So it is possible.
2, [[1,0],[0,1]]
There is a total of 2 courses to take. To take course 1 should has finished course 0, and to take course 0 you should also has finished course 1. So it is impossible.
Problem solving idea One:
Put each node in the diagram, then the BFS for each node, if there is a self-loop, false, otherwise the return True,java implementation is as follows:
Static public boolean canfinish (int numcourses, int[][] Prerequisites) {if (Prerequisites.length = = 0 | | prerequisites [0].length = = 0] return true; Hashmap<integer, undirectedgraphnode> HM = new Hashmap<integer, undirectedgraphnode> (); For (int[] nums:prerequisites) for (int i = 0; i < nums.length-1; i++) {if (!hm.containskey (nums [i])) Hm.put (Nums[i], new Undirectedgraphnode (nums[i)); if (!hm.containskey (nums[i + 1])) Hm.put (Nums[i + 1], new Undirectedgraphnode (Nums[i + 1]); Hm.get (Nums[i]). Neighbors.add (Hm.get (nums[i + 1])); } iterator<integer> Iterator = Hm.keyset (). Iterator (); while (Iterator.hasnext ()) if (Haveloop (Hm.get (Iterator.next ()))) return false; return true;} Static Boolean haveloop (Undirectedgraphnode root) {hashmap<undirectedgraphnode, boolean> HM = new hashmap< Undirectedgraphnode, boolean> (); Queue<undirectedgraphnode> queue = new linkedlist<undirectedgraphnode> (); Hm.put (root, true); Queue.add (root); while (! Queue.isempty ()) {Undirectedgraphnode temp = Queue.poll (); for (Undirectedgraphnode temp2:temp.neighbors) {if (Temp2 = = R OOT) return true;if (!hm.containskey (TEMP2)) {Hm.put (Temp2, True); Queue.add (TEMP2);}}} return false;}
The problem with Tle is that judging whether there is a ring to the graph, it is a waste of time to judge each node%>_<%
Java for Leetcode 207 Course Schedule "unsolved"