我试图使用递归方法实现基于深度优先搜索的两个函数。我最终试图将运行时与warshall的算法(我已经工作)进行比较。当我打印我的矩阵时,它会被一对关闭的路径关闭。递归查找图矩阵DFS中的所有路径DFS
递归是什么可能会把我扔掉,这是我的弱点。由于顶部if语句if(iIndex1 == iIndex2) return TRUE;
,当我尝试查找是否存在来自(A,A),(B,B),(C,C)等的路径时,即使没有路径,我也将始终获得1
从A到A
typedef enum { FALSE, TRUE } bool;
/* Recursive function will determine if there is a path from index 1 to 2
* Based of DFS
*/
bool recPathExists(Graph G, int iIndex1, int iIndex2)
{
int j;
G.nodeArray[iIndex1].visited = TRUE;
if(iIndex1 == iIndex2){
return TRUE;
}
for(j = 0; j < G.iNumNodes; j++){
if(!G.nodeArray[j].visited && G.adjMatrix[iIndex1][j]==1){
if(recPathExists(G, j, iIndex2))
return TRUE;
}
}
return FALSE;
}
/* Write a function to find all pairs of nodes which have paths between them.
* Store this information in the provided pathMatrix.
*/
void allPathsRecFunc(Graph G , int **pathMatrix)
{
int i, j;
for(i = 0; i < G.iNumNodes; i++){
for(j = 0; j < G.iNumNodes; j++){
if(recPathExists(G, i , j)== TRUE){
pathMatrix[i][j] = 1;
}
resetVisited(G); //resets all nodes to FALSE
}
}
}
它应该是
A 0 1 1 1 1 1 1 1
B 0 1 0 0 1 1 1 1
C 0 1 0 0 1 1 1 1
D 0 0 0 0 0 0 0 0
E 0 0 0 0 0 0 0 0
F 0 1 0 0 1 1 1 1
G 0 1 0 0 1 1 1 1
H 0 1 0 0 1 1 1 1
我得到什么
A 1 1 1 1 1 1 1 1
B 0 1 0 0 1 1 1 1
C 0 1 1 0 1 1 1 1
D 0 0 0 1 0 0 0 0
E 0 0 0 0 1 0 0 0
F 0 1 0 0 1 1 1 1
G 0 1 0 0 1 1 1 1
H 0 1 0 0 1 1 1 1
“错误的结果”:*错误*以哪种方式?顺便说一句,尽量保持对'{}'的使用一致(我建议始终使用它们,即使对于单语句循环),并且:如果递归是答案,那么通常像C这样的绝大多数命令式语言不是选择工具。 –
@MarcusMüller我通过使用warshall的算法知道最终的矩阵应该是什么。我使用这个来比较它通过这个方法得到的矩阵结果。该矩阵显示1的地方应该是0,反之亦然。只有大约一半是准确的。 –
@hnefatl递归函数用于确定从iIndex1节点到iIndex2节点的图形中是否存在路径,这是基于DFS算法的。需要for循环来检查所有相邻节点。我还需要在找到它们时标记访问的节点。 –