难以掌握递归思维,到目前为止我在 Stack Overflow 上看到的很多内容我都不明白。
我试图在有向图中检测一个循环,给定一个二维数组邻接矩阵,其中 graph[i][j] 的值为 true 表示从 i 到 j 的边。
已经创建了一个 check_cycles 函数,它检查从 j 到 i 的路径,给定 graph[i][j] 并硬编码了图的大小以简化问题。
使用此代码,我得到了预期的 true 返回值,但是正如您所看到的,现在我已经硬编码了很多 for 循环,如果更改传递给函数的大小或值,这将是不切实际的。
我将如何找到一个递归解决方案?函数应该停止运行的情况是什么?
现在我正在使用一个允许函数返回布尔值的库,但它也可以返回 void。
#include <stdio.h>
#include <cs50.h>
//hard coding the size of the graph
int size = 5;
//set up an adjecency matrix
bool graph[5][5];
//functions
bool check_cycles(int index1, int index2);
int main(void)
{
//setting the graph values to false
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
graph[i][j] = false;
}
}
//hard coding a cycle into the graph
graph[0][1] = true;
graph[1][2] = true;
graph[2][3] = true;
graph[3][0] = true;
//check for cycles
printf(check_cycles(2,3)? "Cycle detected\n" : "No cycles\n");
}
bool check_cycles(int index1, int index2)
{
for (int i = 0; i < size; i++)
{
//check for adjacent edge
if (graph[index2][i] == true)
{
//check if edge points to initial node
if (graph[i][index1] == true)
{
return true;
}
else
{
for (int j = 0; j < size; j++)
{
if (graph[i][j] == true)
{
if (graph[j][index1] == true)
{
return true;
}
else
{
for (int k = 0; k < size; k++)
{
if (graph[j][k] == true)
{
if (graph[k][index1] == true)
{
return true;
}
}
}
}
}
}
}
}
}
return false;
}