pythonpython-3.xlistspiral

How can I use a loop to get clockwise spiral output in matrix as an independent output?


This image explains the problem I'm trying to solve.

And here is my attempted solution:

matrix = [[1, 2, 3, 4, 5],
      [6, 7, 8, 9, 10],
      [11, 12, 13, 14, 15],
      [16, 17, 18, 19, 20]]
i = 0
y = (len(matrix)-1)
while i < len(matrix):
    if i == 0:
        # print 1st row.
        for rows in matrix[i]:
            print(rows)

    # print all the last element of every rows, except 1st and last row.
    elif i != 0 and i != y:
        print(matrix[i][-1])

    # print the last row in reverse.
    elif i == y and i != 0:
        matrix[i].sort(reverse=True)
        for row in matrix[i]:
            print(row)

        print(matrix[i-1][0])       # print the 1st element of 3rd row.

        # print the 1st four elements of 2nd row.
        for r in matrix[1][0:4]:
            print(r)

        # finally print the rest of the elements in reverse.
        matrix[2].sort(reverse=True)
        for r_remain in matrix[2][1:4]:
            print(r_remain)

    i += 1

My question is, is this algorithm right or wrong?

Secondly, my algorithm depends on the size and contents of the input matrix. How can I make it work for any input?


Solution

  • One can obtain a very short solution using numpy, although that is perhaps not in the spirit of the assignment (the library does most of the work):

    import numpy
    
    matrix = [[ 1,  2,  3,  4,  5],
              [14, 15, 16, 17,  6],
              [13, 20, 19, 18,  7],
              [12, 11, 10,  9,  8]]
    
    def recurse(matrix):
        if not len(matrix): return
        for el in matrix[0]: print(el)
        recurse(numpy.rot90(matrix[1:]))
    
    recurse(numpy.array(matrix))