Spiral matrix || leetcode problem
The Spiral Matrix problem takes a 2-Dimensional array of N-rows and M-columns as an input, and prints the elements of this matrix in spiral order.
Get Devesh Tiwari’s stories in your inbox
Join Medium for free to get updates from this writer.
The spiral begins at the top left corner of the input matrix, and prints the elements it encounters, while looping toward the center of this matrix, in a clockwise manner.
HOW DO SPIRAL MATRIX ALGORITHMS WORKS?
First, four variables containing the indices for the corner points of the array are initialized.
The algorithm starts from the top left corner of the array, and traverses the first row from left to right. Once it traverses the whole row it does not need to revisit it, thus, it increments the top corner index.
Once complete, it traverses the rightmost column top to bottom. Again, once this completes, there is no need to revisit the rightmost column, thus, it decrements the right corner index.
Next, the algorithm traverses the bottommost row and decrements the bottom corner index afterward.
Lastly, the algorithm traverses the leftmost column, incrementing the left corner index once it’s done.
This continues until the left index is greater than the right index, and the top index is greater than the bottom index.
Code:-
Python:-
class Solution:
def generateMatrix(self, n):
matrix = [[0] * n for _ in range(n)]
x, y, dx, dy = 0, 0, 1, 0
for i in range(n*n):
matrix[y][x] = i + 1
if not 0 <= x + dx < n or not 0 <= y + dy < n or matrix[y+dy][x+dx] != 0:
dx, dy = -dy, dx
x, y = x + dx, y + dy
return matrix



