我正在用 C 编写以下程序。
这个程序是一个邻接矩阵,它要求用户设置节点之间的连接,然后检查节点 A 和节点 B 之间是否存在连接。
# include <stdio.h>
# include <stdlib.h>
#define N 11
#define FALSE 0
#define TRUE 1
typedef int adj_mat[N][N]; /*defining adj_mat */
int path (adj_mat A, int u, int v);
主要功能要求用户制作有向图,然后要求用户输入两个节点以检查它们是否存在节点 A 和节点 B 之间的连接。
int main()
{
adj_mat Matrix; /*intializing a new graph adjacency matrix.
on this moment nodes are disconnected every cell contains zero */
int dadnode, sonnode; /*intializing dad node and son node*/
printf("Hello. Enter now the pairs of connected nodes.\n");
printf("enter EOF after finishing of connecting all the nodes\n");
do { /*here user enter the nodes to connect */
printf("Enter the number of first node\n");
scanf("%d", &dadnode);
printf("Enter the number of second node\n");
scanf("%d", &sonnode);
if ((dadnode < sonnode) && (sonnode <= N) && (dadnode > 0)) /*checking if nodes are legal*/
Matrix[dadnode][sonnode] = 1; /*if legal - connect*/
} while ( (dadnode != EOF ) && (sonnode != EOF)); /*until user enter EOF */
printf("Now enter u and v nodes to check if exists way from u node to we node\n");
/*here user enter the nodes to check */
printf("Enter the number of u node\n");
scanf("%d", &dadnode);
printf("Enter the number of v node\n");
scanf("%d", &sonnode);
if ((dadnode < sonnode) && (sonnode <= N) && (dadnode > 0)) /*checking if nodes are legal*/ {
if( path(Matrix,dadnode,sonnode) == TRUE ) /*if exisits way from u to v*/
printf ("Exists way from node u to node v ");
}
else printf ("Not exists way from node u to node v ");
}
如果存在从 u(dad node) 到 v(son node) 的方式,则以下函数返回 TRUE,否则返回 FALSE
int path (adj_mat A, int u, int v) {
if (v >= u) /*no sense to check if dad node yonger than son node or dad of himself */
return FALSE;
int nodenum; /*number of node*/
/* "nodenum = v - 1" because node v cannot be son of node >= v */
for(nodenum = v - 1; nodenum > 0; nodenum-- ) {
if (A[nodenum][v] == TRUE) /*dad detected*/
{
if (nodenum == u) {
return TRUE; //complete
} else if (path (A, u, nodenum)) {
return TRUE; //maybe dad is a node that we are looking for (recursion)
}
}
}
return FALSE; /*all parents of v node were cheked and noone of them isnt u node*/
}
最后,我在 gdb (ubuntu) 中运行它。
do { /*here user enter the nodes to connect */
printf("Enter the number of first node\n");
scanf("%d", &dadnode);
printf("Enter the number of second node\n");
scanf("%d", &sonnode);
if ((dadnode < sonnode) && (sonnode <= N) && (dadnode > 0)) {/*checking if nodes are legal*/
Matrix[dadnode][sonnode] = 1; /*if legal - connect*/
}
} while ( (dadnode != EOF ) && (sonnode != EOF)); /*until user enter EOF */
为什么当我试图通过按 Ctrl+d 来停止这个循环(从 main 函数)时,只有在找到其中一个数字为 -1 的一对数字后,循环才会继续并停止?
好的,输入“-1”然后主函数应该调用path()函数来检查节点a和节点b是否连接。如果是,那么它应该根据路径(Matrix,dadnode,sonnode)的结果输出一条消息。
但是,我收到消息“程序正常退出”,而不是这种行为。为什么我会收到此消息?
main 函数甚至调用 path() 函数吗?我不确定我的代码中的错误是什么......