Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filling a n*n matrix with n elements

Tags:

python

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.

like image 267
nish Avatar asked Feb 26 '26 18:02

nish


1 Answers

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
like image 177
Sylvain Leroux Avatar answered Mar 01 '26 09:03

Sylvain Leroux