gpt4 book ai didi

c - 广度优先搜索 - 错误的结果

转载 作者:太空宇宙 更新时间:2023-11-04 04:03:50 25 4
gpt4 key购买 nike

这段代码实现了广度优先搜索。

#define N 9     //nodes
#define MAXNUM 65555
#define FALSE 0
#define TRUE 1

int main() {
int i, j;
int network[N][N]; //Adjacency matrix
int dist[N]; //distances from node u
int u = 0; //choose first node
void bfs(int, int [N][N], int [N]);

for (i = 0; i < N; i++) {
dist[i] = MAXNUM;
for (j = 0; j < N; j++) {
if (i == j) {
network[i][j] = 0;
} else {
network[i][j] = MAXNUM;
network[j][i] = MAXNUM;
}
}
}

network[0][1]=1; network[0][3]=1; network[0][5]=1;
network[1][0]=1; network[1][2]=1; network[1][6]=1;
network[2][1]=1; network[2][3]=1; network[2][7]=1;
network[3][0]=1; network[3][2]=1; network[3][4]=1;
network[4][3]=1; network[4][5]=1; network[4][7]=1;
network[5][0]=1; network[5][4]=1; network[5][6]=1;
network[6][1]=1; network[6][5]=1; network[6][7]=1;
network[7][2]=1; network[7][4]=1; network[7][6]=1;

bfs(u, network, dist);

return 0;
}

void bfs(int u, int network[N][N], int dist[N]) {
int w, v, onScanQ[N], ScanQ[N], Qsize = 0;
int k;

for (v = 0; v < N; v++) {
dist[v] = MAXNUM;
onScanQ[v] = FALSE;
}

dist[u] = 0;
ScanQ[1] = u;
onScanQ[u] = TRUE;
Qsize = 1;
k = 1;

printf("\nBFS has started examining:\n");

do {
v = ScanQ[k];
printf("%d ", v);
for (w = 0; w < N; w++) {
if ((network[v][w] < MAXNUM) && (!onScanQ[w])) {
Qsize++;
ScanQ[Qsize] = w;
onScanQ[w] = TRUE;
dist[w] = dist[v] + 1;
printf("(%d) ", w);
}
k++;
}
} while (k <= Qsize);
printf("\n");}

但不是这些结果:

BFS has started examining: 0 (1) (3) (5) 1 (2) (6) 3 (4) 5 2 (7) 6 4 7

我从输出中获取,只有这个:

BFS has started examining: 0 (1) (3) (5)

缺少什么?

最佳答案

while 循环内的快速 printf 显示您在 while 中的条件不等同于 true 因此仅打印一组输出!

    printf("Qsize=%d k=%d\n", Qsize, k); 
} while (k <= Qsize);

输出:

Qsize=4 k=10

关于c - 广度优先搜索 - 错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8624715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com