3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Python】隣接行列・隣接リスト変換

Last updated at Posted at 2019-08-13

隣接行列

gg = np.array([
    [0, 1, 1, 0, 0, 0, 0],
    [1, 0, 1, 1, 0, 0, 0],
    [1, 1, 0, 0, 1, 0, 0],
    [0, 1, 0, 0, 1, 1, 0],
    [0, 0, 1, 1, 0, 0, 1],
    [0, 0, 0, 1, 0, 0, 0],
    [0, 0, 0, 0, 1, 0, 0]
])

隣接リスト形式

g = np.array([
    [1, 2],     # S
    [3, 4],     # 1 A
    [4, 5],     # 2 B
    [6, 7],     # 3 C
    [8],        # 4 D
    [8, 9],     # 5 E
    [999],      # 6 F
    [10,11],    # 7 H
    [12,13],    # 8 I
    [999],      # 9 J
    [999],      # 10 K
    [999],      # 11 L
    [999],      # 12 G
    [999]       # 13 M
])

隣接行列⇒隣接リスト変換

print("g = np.array([")
for i in range(len(gg)):
    #print(gg[i])
    gyou=[]       
    for j in range(len(gg[0])):
        #print(gg[i,j])
        if gg[i,j]>0:
           gyou.append(j)
    print(chr(9)+str(gyou)+",")
print("])")

隣接リスト⇒隣接行列変換

L=len(g)
#0配列作成
gg=np.zeros((L,L),dtype = int)
for i in range(L):
    for j in range(len(g[i])):
        gg[i,g[i][j]]=1

print("gg = np.array([")
for i in range(L):
    print(gg[i])
print("])")   
3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?