Spiral Matrix Generator is a modular CLI utility designed to calculate and display square matrices filled in a clockwise spiral. Born as a pure logic and index management exercise, this project serves as an excellent example of advanced 2D array manipulation.
What's New in v1.0:
This version leverages modern Python constructs, ditching clunky if/elif chains in favor of a clean, performant approach using the match-case statement introduced in Python 3.10.
- ⚡ O(n²) Algorithm: Traverses and populates the matrix in a single pass, without unnecessary recalculations or overhead.
- 🛡️ Zero Dependencies: Built entirely with pure Python (Standard Library). No
pip installor external packages required. - Modular Architecture: Clean separation of concerns between core calculation logic, formatting, and console rendering.
- Pointer-Based Logic: Utilizes dynamic boundaries that cyclically converge toward the center to determine the optimal path.
See the application output directly in your terminal. Spacing is handled automatically to maintain perfect alignment, regardless of the matrix size!
Enter the matrix dimension (n): 5
Spiral Matrix 5x5:
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
The project structure is minimal, clean, and straight to the point.
.
├── spiral_matrix.py # Entry point & Core Logic
└── README.md # Project Documentation
Since no external libraries are needed, just clone the repository and navigate into the folder:
git clone https://github.com/GiZano/spiral-matrix.git
cd spiral-matrixWarning
Version Requirement: The core algorithm uses syntax introduced in Python 3.10 (match-case). Make sure your system interpreter is up to date before running the script.
python spiral_matrix.pyIf the script is executed with Python 3.9 or lower, a SyntaxError will be raised due to the match block.
Instead of fetching external APIs, this tool orchestrates a precise "dance" of indices. Here are the 4 cyclical phases of the logic engine used to generate the spiral:
| Direction | Movement Axis | Boundary Operation |
|---|---|---|
| ➡️ Right | Top Row | Increment the starting row index (r_start += 1) |
| ⬇️ Down | Right Column | Decrement the ending column index (c_end -= 1) |
| ⬅️ Left | Bottom Row | Decrement the ending row index (r_end -= 1) |
| ⬆️ Up | Left Column | Increment the starting column index (c_start += 1) |
The main() function is designed to be resilient to user typos. Input operations are wrapped safely in a try-except block. In the event of:
- Inputting strings or characters instead of integers (
ValueError) - Zero or negative numbers
The application catches the exception, prints a user-friendly warning message, and triggers a graceful exit without cluttering the console with messy stack traces.
Developed with ☕ and logic