Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Track Solutions #26

Open
wants to merge 41 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
spiral matrix
Aayush Badoni authored and Aayush Badoni committed Apr 16, 2024
commit bd3666ec172da56d67c8a34db5e17113dad5cc82
Binary file not shown.
Binary file not shown.
30 changes: 29 additions & 1 deletion practice/spiral-matrix/spiral_matrix.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,30 @@
"""
Spiral Matrix - spiral_matrix generates a square matrix of a given size in a spiral pattern.
It initializes a matrix with None values and then fills it with numbers in a spiral pattern.
The function uses itertools.cycle to iterate through a cycle of movement directions:
(0,1) for moving right, (1,0) for moving down, (0,-1) for moving left, and (-1,0) for moving up.
The matrix is filled in a spiral pattern by updating the current cell's position and direction
based on the cycle and checking for boundaries and filled cells.
"""

from itertools import cycle

def spiral_matrix(size):
pass
matrix = [[None] * size for _ in range(size)]
r, c = 0, 0
# this cycle determines the movement of the "current cell"
# (0,1) represents moving along a row to the right
# (1,0) represents moving down a column
deltas = cycle(((0,1), (1,0), (0,-1), (-1,0)))
dr, dc = next(deltas)
for i in range(size**2):
matrix[r][c] = i+1
if (
not 0 <= r+dr < size or
not 0 <= c+dc < size or
matrix[r+dr][c+dc] is not None
):
dr, dc = next(deltas)
r += dr
c += dc
return matrix