I want to fill a nxn matrix with n elements, such that each row and each column has exactly 1 element. E.g. a 3x3 matrix can have following as possible solutions:
1 0 0 0 1 0 0 0 1
0 1 0 1 0 0 1 0 0
0 0 1 0 0 1 0 1 0
Following is the code i wrote:
arr=[[0 for x in xrange(n)] for x in xrange(n)]
i=0
while i<n:
j=0
while j<n:
arr[i][j]=0
j+=1
i+=1
i=0
while i<n:
j=0
while j<n:
x=0
while x<n:
if((arr[i][x-1]==1) or (arr[x-1][j]==1)):
break
x+=1
if(x==n-1 and arr[i][n-1]==0 and arr[n-1][j]==0):
arr[i][j]=1
j+=1
i+=1
But all the elements are stiil 0. Could someone please point out my mistake.
Concerning your code:
arr=[[0 for x in xrange(n)] for x in xrange(n)]
The following loop is redundant since the matrix is already initialized to 0:
i=0
while i<n:
j=0
while j<n:
arr[i][j]=0
j+=1
i+=1
Some changes inline now:
i=0
while i<n:
j=0
while j<n:
ok = True
x=0
while x<n:
# Why 'x-1' here?
if((arr[i][x]==1) or (arr[x][j]==1)):
ok = False
break
x+=1
if ok:
arr[i][j]=1
j+=1
i+=1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With