Turning matrix into list of integers as a spiral of given matrix

165 views Asked by At

In below program the output should print the list of integers in spiral of matrix given in program.

Output is : [1, 2, 3, 6, 9, 8, 7, 4, 5, 5]

At the end of the output list the last loop is again printing in reverse order (5 at the end of list is again printing). Why? Where is mistake in my code?

A = [
    [ 1, 2, 3 ],
    [ 4, 5, 6 ],
    [ 7, 8, 9 ]
]

def spiralOrder(A):

    result = []
    t = 0
    b = len(A)-1
    l = 0
    r = len(A[0])-1
    d = 0
    k = 0
    while(t<=b and l<=r):
        if d == 0:
            for i in range(l,r+1):
                result.append(A[t][i])
            t =+ 1
            d = 1
        elif d == 1:
            for i in range(t,b+1):
                result.append(A[i][r])
            r -= 1
            d = 2
        elif d == 2:
            for i in range(r,l-1,-1):
                result.append(A[b][i])
            b -= 1
            d = 3
        elif d == 3:
            for i in range(b,t-1,-1):
                result.append(A[i][l])
            l += 1
            d = 0
    return result

print spiralOrder(A)
2

There are 2 answers

0
Anindya Dutta On

You are updating t =+ 1 where you should be doing t += 1 instead. (in d==0 condition).

0
thodic On

It is the second result.append() statement which adds the last 5. This is because t is the wrong value at this point. Switching t =+ 1 for t += 1 fixes this.


Why

t =+ 1 is the same as t = +1 or t = 1 (no incrementing going on here).

t += 1 increments t by one each call.


Tips

This is a prime candidate for using the python debugger. Many IDEs will have this built in. Place break points on each of your result.append() statements and step through your code, you will quickly see what is going wrong.

Also your variable names are completely cryptic and make it extemely hard to work out what your code is trying to do. Check out clean code and variable names, especially if your code is going to be read by anyone else (like the people of SO).