基于DFS的Java无向图环计数代码运行结果不符问题排查
问题原因
你的代码存在两个核心错误:
- 类静态计数变量
count没有在每次统计不同长度环前重置,多次调用countCycles时计数会累加,导致结果错误。 - 局部变量和静态变量同名容易引发逻辑混淆,虽然不直接影响运行,但属于不规范的编码习惯。
修正方案
- 在
countCycles函数入口处先将静态变量count重置为0,保证每次统计不同长度环时都是从0开始计数。 - 将
count函数中累加总环数的局部变量改名避免同名冲突。
修正后完整代码
public class Main { public static final int V = 5; static int count = 0; static void DFS(int graph[][], boolean marked[],int n, int vert, int start) { marked[vert] = true; if (n == 0) { marked[vert] = false; if (graph[vert][start] == 1) { count++; return; } else return; } for (int i = 0; i < V; i++) if (!marked[i] && graph[vert][i] == 1) DFS(graph, marked, n-1, i, start); marked[vert] = false; } static int countCycles(int graph[][], int n) { count = 0; // 新增:每次统计前重置计数 boolean marked[] = new boolean[V]; for (int i = 0; i < V - (n - 1); i++) { DFS(graph, marked, n-1, i, i); marked[i] = true; } return count / 2; } public static int count(int graph[][]) { int total = 0; // 改名避免和静态变量重名 for(int i=3;i<6;i++) //i starts at 3 because the minimum length of a cycle is 3. total += countCycles(graph,i); return total; } // driver code public static void main(String[] args) { int graph[][] = {{0, 1, 0, 1, 0}, {1, 0, 1, 0, 1}, {0, 1, 0, 1, 0}, {1, 0, 1, 0, 1}, {0, 1, 0, 1, 0}}; System.out.println("Total cycles are "+count(graph)); } }
运行修正后的代码,输出结果为Total cycles are 3,符合预期。
内容的提问来源于stack exchange,提问作者KSP
相关产品推荐
相关产品推荐

