Python Program to Print a Spiral Matrix
A spiral matrix is a matrix with elements arranged in a spiral pattern. In this article, we’ll learn how to create a spiral matrix using Python.
Creating a Spiral Matrix in Python
To create a spiral matrix in Python, we need to follow these steps:
- Initialize the matrix with zeros.
- Set the starting values for the row, column, and direction variables.
- Iterate over the matrix and set the values.
Let’s take a look at the Python code to create a spiral matrix:
def create_spiral_matrix(n):
matrix = [[0 for x in range(n)] for y in range(n)]
row = 0
col = 0
direction = 0
for i in range(n * n):
matrix[row][col] = i + 1
if direction == 0:
if col < n - 1 and matrix[row][col + 1] == 0:
col += 1
else:
direction = 1
row += 1
elif direction == 1:
if row < n - 1 and matrix[row + 1][col] == 0:
row += 1
else:
direction = 2
col -= 1
elif direction == 2:
if col > 0 and matrix[row][col - 1] == 0:
col -= 1
else:
direction = 3
row -= 1
elif direction == 3:
if row > 0 and matrix[row - 1][col] == 0:
row -= 1
else:
direction = 0
col += 1
return matrix
# testing the function
n = 5
matrix = create_spiral_matrix(n)
for i in range(n):
for j in range(n):
print(matrix[i][j], end="\t")
print()
Output:
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
In the code above, we first initialize the matrix with zeros, then set the starting row, column, and direction variables. We then iterate over the matrix and set the values based on the current direction.
We use the if
statements to check if we’re at the edge of the matrix or if we’re about to overwrite a previously set value. If either of these conditions is true, we change the direction variable to move in the next direction.
Conclusion
We’ve just learned how to create a spiral matrix in Python. With this technique, we can now create spiral patterns in our programs. The spiral matrix can be useful in a variety of applications, such as for generating graphics or for data visualization.