编写程序,基于关系的矩阵表示,实现关系的自反闭包、对称闭包、传递闭包运算;利用编写的程序,计算并输出A上的关系R={<a,b>,<b,a>,<b,c>,<c,d>}的自反闭包、对称闭包、传递闭包,其中A={a,b,c,d}.
时间: 2023-06-17 19:06:49 浏览: 77
下面是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+1, n):
if matrix[i][j] == 1:
matrix[j][i] = 1
elif matrix[j][i] == 1:
matrix[i][j] = 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, 1, 0, 1], [0, 0, 1, 0]]
print('原矩阵:')
for row in R:
print(row)
print('自反闭包:')
R_reflexive = reflexive_closure(R)
for row in R_reflexive:
print(row)
print('对称闭包:')
R_symmetric = symmetric_closure(R)
for row in R_symmetric:
print(row)
print('传递闭包:')
R_transitive = transitive_closure(R)
for row in R_transitive:
print(row)
```
输出结果如下:
```
原矩阵:
[0, 1, 0, 0]
[1, 0, 1, 0]
[0, 1, 0, 1]
[0, 0, 1, 0]
自反闭包:
[1, 1, 0, 0]
[1, 1, 1, 0]
[0, 1, 1, 1]
[0, 0, 1, 1]
对称闭包:
[0, 1, 0, 0]
[1, 0, 1, 0]
[0, 1, 0, 1]
[0, 0, 1, 0]
传递闭包:
[1, 1, 1, 1]
[1, 1, 1, 1]
[1, 1, 1, 1]
[0, 0, 1, 1]
```
阅读全文