I want to create a matrix thats N by N and that N is recieved as an input and when it prints its printed in a spiral. For example if the input is a 4 that means the matrix will be 4 by 4 and it will look like this when printed:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
I know how to create the matrix and make it N by N what I do not know is how can I make it look like this. Is there any guide,tutorial or anything I can watch/read to get how to make more 2d array exercises?
def llenar_matriz(n):
# Fills the matrix
for r in range(n):
fila = []
for c in range(n):
fila.append(0)
matriz.append(fila)
return matriz
def imprimir_matriz(matriz):
# Prints the matrix
filas = len(matriz)
columnas = len(matriz[0])
for f in range(filas):
for c in range(columnas):
print ("=" %matriz[f][c], end="")
print()
# Main program
lado = int(input("Ingrese el tamaño de la matriz: "))
while lado < 1:
print("Tamaño inválido. Debe ser mayor que 0")
lado = int(input("Ingrese el tamaño de la matriz: "))
matriz = []
llenar_matriz(lado)
imprimir_matriz(matriz)
This is my code atm and all it does is create a matrix of N by N, fills it with 0's and prints it
CodePudding user response:
Algorithm :Let the array have R rows and C columns. seen[r] denotes that the cell on the r-th row and c-th column was previously visited. Our current position is (r, c), facing direction di, and we want to visit R x C total cells.
As we move through the matrix, our candidate’s next position is (cr, cc). If the candidate is in the bounds of the matrix and unseen, then it becomes our next position; otherwise, our next position is the one after performing a clockwise turn.
Code:
def spiralOrder(matrix):
ans = []
if (len(matrix) == 0):
return ans
R = len(matrix)
C = len(matrix[0])
seen = [[0 for i in range(C)] for j in range(R)]
dr = [0, 1, 0, -1]
dc = [1, 0, -1, 0]
r = 0
c = 0
di = 0
# Iterate from 0 to R * C - 1
for i in range(R * C):
ans.append(matrix[r])
seen[r] = True
cr = r dr[di]
cc = c dc[di]
if (0 <= cr and cr < R and 0 <= cc and cc < C and not(seen[cr][cc])):
r = cr
c = cc
else:
di = (di 1) % 4
r = dr[di]
c = dc[di]
return ans
# Driver code
a = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
for x in spiralOrder(a):
print(x, end=" ")
print()
This is a Pic of how it works:
CodePudding user response:
Here is a way using numpy
:
# initialize test array
a = np.arange(16).reshape(4,4)
# spiral reshaping
out = []
while a.size:
out.append(a[0]) # take first row
a = np.rot90(a[1:]) # remove 1st row, rotate counter-clockwise
out = np.concatenate(out) # concatenate output
Explanation: take first row, rotate the rest of array, repeat until all the array is gone
input:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
output:
array([ 0, 1, 2, 3, 7, 11, 15, 14, 13, 12, 8, 4, 5, 6, 10, 9])