Matrix

Words
119
Reading
1 min
Listen
Play
2y

RIGHT = 0

DOWN = 1

LEFT = 2

UP = 3

def next_position(i, j, direction):

if direction == RIGHT:

    return i, j+1

if direction == DOWN:

    return i+1,j

if direction == LEFT:

    return i, j-1

return i-1,j # for direction UP

def spiral_matrix(size):

matrix = [[0 for i in range(size)] for j in range(size)]

i = 0

j = 0

direction = RIGHT

for n in range(1,(size\*\*2)+1):

    matrix[i][j] = n

    i\_test, j\_test = next\_position(i,j,direction)

    if i\_test not in range(size) or j\_test not in range(size) or matrix[i\_test][j\_test]!=0:

        if direction == UP: 

            direction = RIGHT

        else: # funziona con valori messi da noi perche´ messi nell´ordine giusto 

            direction +=1

    i, j = next\_position(i, j, direction)

return matrix
Matrix | Ecency