from numpy import *
import numpy
import random
import itertools
def check(v): #判斷是否是迴路
i3,i4,i5,i6=0,0,0,0
t=1
c= numpy.zeros((m, n)) #建立一個與電路矩陣相同大小的零矩陣
for i3 in v:
c[:, int(i3)] = a1[:, int(i3)]
for i4 in range(m): #將後面所有列的元素與全部加到第一列
for i5 in range(n-1):
c[i4,0]+= c[i4,i5+1]
for i6 in range(m): #判斷第一列是都有0元素
if c[i6,0]==0:
t=0
break
if t==1:
return 1 #無0即不是迴路,返回1 輸出
else:
return 0 #有0即是迴路,返回0 不輸出輸出
def C(n,i): #確定組合個數
#n>=i
Min=min(i,n-i)
result=1
for j in range(0,Min):
result=result*(n-j)/(Min-j)
return result
#電路圖定義部分
if __name__ == '__main__':
m = int(input("請輸入節點數"))
n = int(input("請輸入支路數"))
i = 0
j = 0
c = 0
count = 0
shu_num=0
input1 = list(input("請輸入電路圖對應矩陣"))
for c in range(m - 1):
input1.remove(' ') #移除字串中的空格鍵
q = list(input1)
a1 = numpy.zeros((m, n))
for i in range(m):
for j in range(n):
a1[i,j] = int(q[count]) #將list中的每一個元素分別給矩陣按行賦值
count += 1
list1 = []
b=[]
for i in range(n):
list1.append(i) #list1存放1-n個數用來產生所有組合
list2 = list(itertools.combinations(list1, m-1))
num = int(C(n, m - 1)) #呼叫C函數
for i in range (num):
if check(list2[i])==1: #呼叫check 檢查是否是迴路函數
shu_num+=1
b = [m + 1 for m in list2[i]]
print("該電路圖的樹",shu_num,b)
程式碼驗證: