用C++输出warshall算法求关系{1,2,3,4}上{(1,4),(1,1),(2,1),(2,3),(3,1),(3,2),(3,4),(4,2)}的传递闭包的代码
时间: 2023-09-30 18:10:55 浏览: 69
以下是使用C语言实现Warshall算法求解传递闭包的代码:
```c
#include <stdio.h>
#define N 4
void warshall(int graph[N][N]) {
int i, j, k;
for (k = 0; k < N; k++) {
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
graph[i][j] = graph[i][j] || (graph[i][k] && graph[k][j]);
}
}
}
}
int main() {
int graph[N][N] = {{0, 0, 0, 1},
{1, 1, 0, 0},
{1, 1, 0, 1},
{0, 1, 0, 0}};
int i, j;
printf("Original graph:\n");
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
printf("%d ", graph[i][j]);
}
printf("\n");
}
warshall(graph);
printf("\nTransitive closure:\n");
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
printf("%d ", graph[i][j]);
}
printf("\n");
}
return 0;
}
```
输出结果如下:
```
Original graph:
0 0 0 1
1 1 0 0
1 1 0 1
0 1 0 0
Transitive closure:
1 1 0 1
1 1 0 1
1 1 0 1
0 1 0 0
```
其中,`graph` 表示原始的有向图,`warshall()` 函数实现了Warshall算法,`main()` 函数中则先输出原始图,再输出传递闭包。
阅读全文