DFS is determined whether or not there has circumferential FIG.
There are three cases to a node, yet access is available, end of the visit
we use 0, 1, -1, is available for representation still not out of recursion, if nodes are connected to access
instructions on accessing the course of a road in DFS the same node twice, indicating that the ring has
the following implemented in code
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
if(findOrder(numCourses,prerequisites))
{
return false;
}
else
{
return true;
}
}
int[] state ;
Map<Integer,List<Integer>> map =new HashMap<Integer,List<Integer>>();
void init(int numCourses, int[][] prerequisites)//初始化操作
{
state = new int[numCourses];//存放状态
for(int i=0;i<numCourses;i++)
{
map.put(i,new ArrayList<Integer>());
}
for(int i=0;i<prerequisites.length;i++)
{
map.get(prerequisites[i][1]).add(prerequisites[i][0]);//建立领接列表存储节点
}
}
public boolean findOrder(int numCourses, int[][] prerequisites) {
init(numCourses,prerequisites);
for(int i=0;i<numCourses;i++)
{
if(DFS(i))
return true;
for(int k=0;k<numCourses;k++)
{
state[k]=0;
}
}
return false;
}
boolean DFS(int start)
{
if(state[start]==-1)//防止出现死循环
{
return false;
}
if(state[start]==1)//正在访问
{
return true;
}
else
{
state[start]=1;
for(int i=0;i<map.get(start).size();i++)
{
if(DFS(map.get(start).get(i)))//发现有环,一直往上回退直到退出
return true;
}
state[start]=-1;
}
return false;
}
}