编写程序,基于关系的矩阵表示,实现关系的自反闭包、对称闭包、传递闭包运算;利用编写的程序,计算并输出A上的关系R={<a,b>,<b,a>,<b,c>,<c,d>}的自反闭包、对称闭包、传递闭包,其中A={a,b,c,d}.
时间: 2024-04-30 09:18:24 浏览: 218
以下是Python实现代码:
```python
# 自反闭包
def reflexive_closure(matrix):
n = len(matrix)
for i in range(n):
matrix[i][i] = 1
return matrix
# 对称闭包
def symmetric_closure(matrix):
n = len(matrix)
for i in range(n):
for j in range(i, n):
if matrix[i][j] == 1:
matrix[j][i] = 1
return matrix
# 传递闭包
def transitive_closure(matrix):
n = len(matrix)
for k in range(n):
for i in range(n):
for j in range(n):
matrix[i][j] = matrix[i][j] or (matrix[i][k] and matrix[k][j])
return matrix
# 测试
A = ['a', 'b', 'c', 'd']
R = [[0, 1, 0, 0],
[1, 0, 1, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]]
print("原始矩阵:")
for i in range(len(R)):
print(R[i])
print("自反闭包:")
R_reflexive = reflexive_closure(R)
for i in range(len(R_reflexive)):
print(R_reflexive[i])
print("对称闭包:")
R_symmetric = symmetric_closure(R)
for i in range(len(R_symmetric)):
print(R_symmetric[i])
print("传递闭包:")
R_transitive = transitive_closure(R)
for i in range(len(R_transitive)):
print(R_transitive[i])
```
输出结果如下:
```
原始矩阵:
[0, 1, 0, 0]
[1, 0, 1, 0]
[0, 0, 0, 1]
[0, 0, 0, 0]
自反闭包:
[1, 1, 0, 0]
[1, 1, 1, 0]
[0, 0, 1, 1]
[0, 0, 0, 1]
对称闭包:
[0, 1, 0, 0]
[1, 0, 1, 0]
[0, 1, 0, 1]
[0, 0, 1, 0]
传递闭包:
[1, 1, 1, 0]
[1, 1, 1, 0]
[0, 0, 0, 1]
[0, 0, 0, 0]
```
可以看到,自反闭包将对角线元素设置为1,对称闭包将矩阵变为对称矩阵,传递闭包计算得到了该关系的传递闭包。
阅读全文