用简单C语言实现输入关系R的矩阵,计算其自反闭包、对称闭包和传递闭包( R+算法),并输出。
时间: 2024-03-05 22:49:50 浏览: 27
好的,以下是用C语言实现输入关系R的矩阵,计算其自反闭包、对称闭包和传递闭包(R+算法)的代码:
```c
#include <stdio.h>
#define MAXSIZE 10
void input(int arr[][MAXSIZE], int n); // 输入矩阵
void output(int arr[][MAXSIZE], int n); // 输出矩阵
void reflexive_closure(int arr[][MAXSIZE], int n); // 计算自反闭包
void symmetric_closure(int arr[][MAXSIZE], int n); // 计算对称闭包
void transitive_closure(int arr[][MAXSIZE], int n); // 计算传递闭包
int main()
{
int arr[MAXSIZE][MAXSIZE], n;
printf("请输入矩阵大小n(n<=10):");
scanf("%d", &n);
printf("请输入关系R的矩阵:\n");
input(arr, n);
printf("\n关系R的矩阵为:\n");
output(arr, n);
reflexive_closure(arr, n);
printf("\n自反闭包为:\n");
output(arr, n);
symmetric_closure(arr, n);
printf("\n对称闭包为:\n");
output(arr, n);
transitive_closure(arr, n);
printf("\n传递闭包为:\n");
output(arr, n);
return 0;
}
void input(int arr[][MAXSIZE], int n)
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", &arr[i][j]);
}
}
}
void output(int arr[][MAXSIZE], int n)
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
void reflexive_closure(int arr[][MAXSIZE], int n)
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (i == j)
{
arr[i][j] = 1;
}
}
}
}
void symmetric_closure(int arr[][MAXSIZE], int n)
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (arr[i][j] == 1)
{
arr[j][i] = 1;
}
else if (arr[j][i] == 1)
{
arr[i][j] = 1;
}
}
}
}
void transitive_closure(int arr[][MAXSIZE], int n)
{
int i, j, k;
for (k = 0; k < n; k++)
{
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (arr[i][k] == 1 && arr[k][j] == 1)
{
arr[i][j] = 1;
}
}
}
}
}
```
这个代码用的是R+算法来计算传递闭包。R+算法的思路是从关系R开始,每次迭代都将两个元素之间的路径长度加1,直到路径长度达到n-1,这时得到的矩阵就是R的传递闭包。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)