用简单C语言实现A={1,2,3,4}上的关系R={<1,1>,<1,2>,<1,4>,<2,1>,<2,2>,<3,2>,<3,4>,<4,2>,<4,4>} 从键盘输入关系R的矩阵,计算其自反闭包、对称闭包和传递闭包(传递闭包使用 R+算法或 Warshall 算法),并输出。
时间: 2024-03-05 14:49:28 浏览: 109
好的,我来为您提供一份简单的C语言代码实现。
首先是读取关系矩阵,这里使用二维数组存储:
```
#include <stdio.h>
#define N 4
int R[N][N];
int main() {
printf("请输入关系矩阵R:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
scanf("%d", &R[i][j]);
}
}
return 0;
}
```
接下来是计算自反闭包,使用循环遍历矩阵并修改元素:
```
for (int i = 0; i < N; i++) {
if (R[i][i] == 0) {
R[i][i] = 1;
}
}
```
然后是计算对称闭包,同样使用循环遍历矩阵并修改元素:
```
for (int i = 0; i < N; i++) {
for (int j = i+1; j < N; j++) {
if (R[i][j] == 1 && R[j][i] == 0) {
R[j][i] = 1;
}
if (R[j][i] == 1 && R[i][j] == 0) {
R[i][j] = 1;
}
}
}
```
最后是计算传递闭包,这里使用 R+算法,循环遍历矩阵并修改元素:
```
int Rt[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
Rt[i][j] = R[i][j];
}
}
for (int k = 0; k < N; k++) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (Rt[i][j] == 0) {
for (int l = 0; l < N; l++) {
if (Rt[i][l] == 1 && Rt[l][j] == 1) {
R[i][j] = 1;
Rt[i][j] = 1;
break;
}
}
}
}
}
}
```
完整代码如下所示:
```
#include <stdio.h>
#define N 4
int R[N][N];
int main() {
printf("请输入关系矩阵R:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
scanf("%d", &R[i][j]);
}
}
// 计算自反闭包
for (int i = 0; i < N; i++) {
if (R[i][i] == 0) {
R[i][i] = 1;
}
}
// 计算对称闭包
for (int i = 0; i < N; i++) {
for (int j = i+1; j < N; j++) {
if (R[i][j] == 1 && R[j][i] == 0) {
R[j][i] = 1;
}
if (R[j][i] == 1 && R[i][j] == 0) {
R[i][j] = 1;
}
}
}
// 计算传递闭包
int Rt[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
Rt[i][j] = R[i][j];
}
}
for (int k = 0; k < N; k++) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (Rt[i][j] == 0) {
for (int l = 0; l < N; l++) {
if (Rt[i][l] == 1 && Rt[l][j] == 1) {
R[i][j] = 1;
Rt[i][j] = 1;
break;
}
}
}
}
}
}
// 输出结果
printf("自反闭包:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d ", R[i][j]);
}
printf("\n");
}
printf("对称闭包:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d ", R[i][j]);
}
printf("\n");
}
printf("传递闭包:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d ", R[i][j]);
}
printf("\n");
}
return 0;
}
```
希望可以帮助到您!
阅读全文