My Coding > Programming language > Python > Exercise > Spiral matrix

Spiral matrix

Print out table n×n with values from 1 to n2 started from top-left corner and spirally go towards the centre of this table.

For example for N=5 we should have this table:


1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9

Solution for spiral matrix

Step 1: Create movement direction matrix, which will be added to current location.
S=[[0,1],[1,0],[0,-1],[-1,0]]

Step 2: After filling first line with values from 1 to n, you can easily notice, that the lengs of the next two lines will be ‘n-1’, then next two lines will be ‘n-2’ etc...until we fill ‘n2’ cells

Step 3: If you think, then this algorithm can easily be transformed to any n×m table, by length of travel ‘m-1’ and ‘n-1’ after first line, then ‘m-2’ and ‘n-2’ and so on, until we fill ‘n*m’ cells.

Python code

This is working Python code implementing this simple algorithm for n×n table


N=int(input()) # input table size
M=[ [0] * N for _ in range(N)] # create n×n table with 0 values
i,j=0,0 # our starting point
c=1 # our starting value
d=0 #direction (0 – right, 1 – down, 2 – left, 3 – up)
S=[[0,1],[1,0],[0,-1],[-1,0]] # shift matrix

# fill first line 
for j in range (N):
  M[i][j]=c
  c += 1
# fill the rest in this cycle
for n in range(N-1,0,-1):
  for p in range(2):
    d += 1
    if d > 3: d = 0
    for k in range(n):
      i+=S[d][0]
      j+=S[d][1]
      M[i][j]=c
      c += 1
# simple output
for i in range(len(M)):
  for j in range(len(M[i])):
    print( M[i][j], end=' ')
  print()

Another solution for spiral matrix

Idea is very simple. Create table n×n with 0 in every cell. Start from top-left corner and place increasing counter in every cell with 0 inside. If the table border is reached, or cell value is non-zero, turn and continue. If the first cell after turn is non-zero, then stop – job done.

This algorithm perfectly works for tables of n×n and n×m sizes.


Published: 2021-09-13 08:06:26
Updated: 2021-09-13 08:10:11

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.