赞
踩
为了最终理解你所不理解的,你必须经历一条愚昧无知的道路。为了占有你从未占有的东西,你必须经历被剥夺的道路。为了达到你现在所不在的名位,你必须经历那条你不在其中的道路。——艾略特
if(n == sz-1){
res.add(result);
}
class Solution {
List<Integer> path = new LinkedList<>();
List<List<Integer>> res = new LinkedList<List<Integer>>();
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
traverse(graph,0);
return res;
}
void traverse(int[][] graph,int n){
path.add(n);
int sz = graph.length;
if(n == sz-1){
List<Integer> result = new LinkedList<>(path);
res.add(result);
}
else{
for(int node:graph[n]){
traverse(graph,node);
}
}
path.remove(path.size()-1);
}
}
List<Integer>[] graph = new LinkedList[numCourses];
for(int i=0;i<numCourses;i++){
graph[i] = new LinkedList<>();
}
class Solution {
boolean[] visited;
boolean[] path;
boolean isCycle = false;
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<Integer>[] graph = generateGraph(numCourses,prerequisites);
visited = new boolean[numCourses];
path = new boolean[numCourses];
for(int i=0;i<numCourses;i++){
traverse(graph,i);
}
return !isCycle;
}
void traverse(List<Integer>[] graph,int n){
if(path[n]){
isCycle = true;
}
if(visited[n]||isCycle){
return;
}
visited[n] = true;
path[n] = true;
for(int node:graph[n]){
traverse(graph,node);
}
path[n] = false;
}
List<Integer>[] generateGraph(int numCourses, int[][] prerequisites){
List<Integer>[] graph = new LinkedList[numCourses];
for(int i=0;i<numCourses;i++){
graph[i] = new LinkedList<>();
}
for(int i=0;i<prerequisites.length;i++){
graph[prerequisites[i][1]].add(prerequisites[i][0]);
}
return graph;
}
}
class Solution {
boolean[] visited;
boolean[] path;
int[] res;
boolean isCycle = false;
int i=0;
public int[] findOrder(int numCourses, int[][] prerequisites) {
List<Integer>[] graph = generateGraph(numCourses,prerequisites);
visited = new boolean[numCourses];
path = new boolean[numCourses];
res = new int[numCourses];
for(int i=0;i<numCourses;i++){
traverse(graph,i);
}
if(!isCycle){
int[] result = new int[numCourses];
for(int i=0;i<numCourses;i++){
result[i] = res[numCourses-i-1];
}
return result;
}else{
return new int[]{};
}
}
void traverse(List<Integer>[] graph,int n){
if(path[n]){
isCycle = true;
}
if(path[n] || visited[n]){
return;
}
visited[n] = true;
path[n] = true;
for(int node:graph[n]){
traverse(graph,node);
}
path[n] = false;
res[i] = n;
i++;
}
List<Integer>[] generateGraph(int numCourses, int[][] prerequisites){
List<Integer>[] graph = new LinkedList[numCourses];
for(int i=0;i<numCourses;i++){
graph[i] = new LinkedList();
}
for(int i=0;i<prerequisites.length;i++){
graph[prerequisites[i][1]].add(prerequisites[i][0]);
}
return graph;
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。