python隣接マトリクスから達マトリクスを計算し、コピーします.
11897 ワード
python計算可達行列
他の人から見たのですが、元のコードに問題があるようで、修正しました.
出力:
他の人から見たのですが、元のコードに問題があるようで、修正しました.
matrix = [[0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0]]
def get_reach_matrix(matrix):
'''
@description:
@matrix {list} list , np.mat
@return: 01
@usage:
matrix = [[0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0]]
get_reach_matrix(matrix)
'''
import numpy as np
A = np.mat(matrix)
I = np.identity(len(A))
newMat = A+I
oldMat = newMat
flag = 0
step = 1
while flag == 0:
oldMat = newMat
newMat = oldMat*(A+I)
for i in range(len(newMat)):
for j in range(len(newMat)):
if newMat[i, j] >= 1:
newMat[i, j] = 1
step += 1
print(step)
if (oldMat == newMat).all():
flag = 1
print(newMat, step)
get_reach_matrix(matrix)
出力:
2
3
4
5
[[1. 0. 1. 0. 1. 0. 1. 0. 1.]
[0. 1. 1. 1. 1. 1. 1. 1. 1.]
[0. 0. 1. 0. 1. 0. 1. 0. 1.]
[0. 0. 0. 1. 1. 1. 1. 1. 1.]
[0. 0. 0. 0. 1. 0. 1. 0. 1.]
[0. 0. 0. 0. 0. 1. 1. 1. 1.]
[0. 0. 0. 0. 0. 0. 1. 0. 1.]
[0. 0. 0. 0. 0. 0. 0. 1. 1.]
[0. 0. 0. 0. 0. 0. 0. 0. 1.]] 5