logoStarPatterns
Back to Patterns

Spiral Pattern

Pattern Result

01 02 03 04 05
16 17 18 19 06
15 24 25 20 07
14 23 22 21 08
13 12 11 10 09

Code Implementation

Explanation

The Spiral Pattern creates a square matrix filled with consecutive numbers in a spiral order. The algorithm starts from the top-left corner and fills the matrix in a clockwise spiral pattern. It uses four pointers (rowStart, rowEnd, colStart, colEnd) to keep track of the boundaries of the unfilled portion of the matrix. In each iteration, it fills the top row, right column, bottom row, and left column of the current boundary, and then shrinks the boundary. The process continues until the entire matrix is filled. Finally, the matrix is converted to a pattern by formatting each number to have two digits and joining the rows with spaces.