I have learnt about graph theory lately and i m trying to implement Kruskal's algorithm to find the min. spanning tree in a graph using a weight matrix.I got a correct output for a matrix and an out of bound error for another! It gave me an error for:
[[1000,16,12,21,1000,1000,1000],[16,1000,1000,17,20,1000,1000],[12,1000,1000,28,1000,31,1000],[21,17,28,1000,18,19,23],[1000,20,1000,18,1000,1000,11],[1000,1000,31,19,1000,1000,27],[1000,1000,1000,23,11,27,1000]]
Matrix for which i got a correct answer is the one below: (NOTE:1000 is used to denote a weight of infinity
vertices=5
spset=[True]*5
wt=[[1000,1,3,4,1000],[1,1000,5,1000,7],[3,5,1000,6,8],[4,1000,6,1000,2],[1000,7,8,2,1000]]
row=[0]
for i in xrange(vertices-1):
row_num,col_num,min_no=-1,-1,1000
for i in row:
temp=min(wt[row[i]])
if(min_no>temp):
min_no=temp
row_num=i
col_num=wt[i].index(temp)
print str(min_no)+"("+str(row_num)+","+str(col_num)+")"
spset[col_num]=False
wt[col_num][row_num]=1000
for i in xrange(vertices):
wt[i][col_num]=1000
row.append(col_num)
d=raw_input()
In the following code block,
for i in row:
temp=min(wt[row[i]])
i
is being iterated over elements of row
. If row
has two elements [0,2]
, then when i
becomes 2, row[i]
will give an IndexError: list index out of range
.
If you want to iterate over elements of row
, use for i in range(len(row))
instead.