在简单的话语中,
树是一种非循环数据结构
,当存在循环时,它就变成了
图
。
![enter image description here](https://istack.dev59.com/EDlWV.webp)
上面是一个图形的示例。您可以使用邻接表或邻接矩阵来表示它。您可以参考
http://krishnalearnings.blogspot.in/2015/11/basics-of-graph-in-computer-science.html了解图形的基础知识。
在上面的图片中,我们可以将其表示为以下形式(在您的问题中,您使用了一种邻接表的表示方法)。
int[][] graph = { {0,1,0,0,0,0},
{0,0,1,0,0,0},
{0,0,0,1,1,0},
{0,0,0,0,0,0},
{0,0,0,0,0,1},
{0,1,0,0,0,0},
};
1代表从相应行编号的顶点到列编号的顶点的一条边。
我们可以编写一个简单的方法来检测图中是否存在环,并打印出其中任意一个环。
static int[] cycleElements;
static int cycleElementIndex = 0;
static boolean cycleFound = false;
static final int NEW = 0;
static final int PUSHED = 1;
static final int POPPED = 2;
public static int findCycle(int[][] graph,int N, int u, int[] states){
for(int v = 0; v < N; v++){
if(graph[u][v] == 1){
if(states[v] == PUSHED){
cycleFound = true;
return v;
}else if(states[v] == NEW){
states[v] = PUSHED;
int poppedVertex = findCycle(graph, N, v, states);
states[v] = POPPED;
if(cycleFound){
if(poppedVertex == u){
cycleElements[cycleElementIndex++] = v;
cycleElements[cycleElementIndex++] = u;
cycleFound = false;
}else{
cycleElements[cycleElementIndex++] = v;
return poppedVertex;
}
}
}
}
}
return -1;
}
public static void main(String[] args) {
int N = 6;
int[][] graph = { {0,1,0,0,0,0},
{0,0,1,0,0,0},
{0,0,0,1,1,0},
{0,0,0,0,0,0},
{0,0,0,0,0,1},
{0,1,0,0,0,0},
};
cycleElements = new int[N];
int[] states = new int[N];
states[0] = PUSHED;
findCycle(graph,N,0,states);
for(int i = 0; i < cycleElementIndex; i++){
System.out.println(cycleElements[i]);
}
}
如果您愿意,可以轻松将上述方法转换为邻接表,尽管表示并不重要(只有邻接表可能会比邻接矩阵节省空间)。