问题
编写一个 JAVA 程序来计算无向图中的循环数。
我的做法:
我尝试使用深度优先搜索来解决这个问题。
我在网上找到了一个程序,可以计算无向连通图中长度为 n 的循环。
代码来自:https ://www.geeksforgeeks.org/cycles-of-length-n-in-an-undirected-and-connected-graph/
我通过创建函数 count() 对其进行了修改。它使用 for 循环检查图中不同长度的循环数。到目前为止我得到的代码附在下面。
我得到的输出是
但是,答案不应该是3吗?
遵循 3 个独特的周期
0 -> 1 -> 2 -> 3 -> 0
0 -> 1 -> 4 -> 3 -> 0
1 -> 2 -> 3 -> 4 -> 1
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)
{
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 count=0;
for(int i=3;i<6;i++) //i starts at 3 because the minimum length of a cycle is 3.
count+=countCycles(graph,i);
return count;
}
// 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));
}
}