判断图是否有环——DFS另类解法
首先对每个结点进行一次DFS遍历,记录所遍历的结点数,取最小值,记作count。
根据count判断是否为连通图:
如果是,直接根据结点数和边数的关系就可判断(边数大于等于结点数则必有回路)
如果不是,若 count + 图的边数 >= 图的结点数,则必存在回路(画图试出来的,这里count必须取最小值,否则判断错误)
Java代码
static class MGraph {
int vexnum;
int arcnum;
boolean[][] Edge;
MGraph(int vex, int arc) {
vexnum = vex;
arcnum = arc;
Edge = new boolean[vexnum + 1][vexnum + 1];
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt(); // 结点数
int m = input.nextInt(); // 边数
MGraph graph = new MGraph(n, m);
for (int i = 0; i < m; i++) { // 所有边
int x = input.nextInt();
int y = input.nextInt();
graph.Edge[x][y] = graph.Edge[y][x] = true;
}
boolean[] visited = new boolean[n + 1];
int count = Integer.MAX_VALUE;
int res = 0;
for(int i = 1; i <= n; i++) {
res = DFS(graph, i, visited, 0);
count = Integer.min(count, res);
}
if(count == graph.vexnum && graph.arcnum >= count)
System.out.println("YES");
else if(count < graph.vexnum && count + graph.arcnum >= graph.vexnum)
System.out.println("YES");
else
System.out.println("NO");
}
public static int DFS(MGraph graph, int v, boolean[] visited, int count) {
visited[v] = true;
count++;
for (int i = 1; i <= graph.vexnum; i++) {
if (graph.Edge[v][i] == true && !visited[i])
return DFS(graph, i, visited, count);
}
return count;
}