https://leetcode-cn.com/problems/course-schedule/
why this algorithm is wrong?
[algorithm]
0 globally have visited node list, keep correct node access order
1 pick one node, do traversal like bfs/dfs
keep accessed node in a list
2 add the previous traversal list to the front of global list
3 pick another node, do the same thing as step 1.
[bug]
class Solution {
Set visited = new HashSet<>();
List[] adj;
public boolean canFinish(int numCourses, int[][] prerequisites) {
int n = numCourses;
adj = new List[n];
for(int i=0;i<n;i++){
adj[i] = new ArrayList<>();
}
for(int i=0;i<prerequisites.length;i++){
int s = prerequisites[i][1];
int t = prerequisites[i][0];
adj[s].add(t);
}
for(int i=0;i<n;i++){
if(visited.contains(i)){
continue;
}
Set path = new HashSet<>();
if(dfs(i, path)==false){
return false;
}
visited.add(path);
}
return true;
}
boolean dfs(int i, Set path, set localVis){
if(visited.contains(i))){
return false;
}
path.add(i);
localVis.add(i)
for(int neigh: adj[i]){
if(dfs(neigh, path)==false){
return false;
}
}
path.remove(path.size()-1);
return true;
}
}