Given a number n as the size of the matrix, the task is to print a spiral pattern of size n.
Examples:
Input : n = 4
Output: 1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
Preview of the Spiral Pattern:
Java
public class GFG {
public static void printSpiral( int size)
{
int row = 0 , col = 0 ;
int boundary = size - 1 ;
int sizeLeft = size - 1 ;
int flag = 1 ;
char move = 'r' ;
int matrix[][] = new int [size][size];
for ( int i = 1 ; i < size * size + 1 ; i++) {
matrix[row][col] = i;
switch (move) {
case 'r' :
col += 1 ;
break ;
case 'l' :
col -= 1 ;
break ;
case 'u' :
row -= 1 ;
break ;
case 'd' :
row += 1 ;
break ;
}
if (i == boundary) {
boundary += sizeLeft;
if (flag != 2 ) {
flag = 2 ;
}
else {
flag = 1 ;
sizeLeft -= 1 ;
}
switch (move) {
case 'r' :
move = 'd' ;
break ;
case 'd' :
move = 'l' ;
break ;
case 'l' :
move = 'u' ;
break ;
case 'u' :
move = 'r' ;
break ;
}
}
}
for (row = 0 ; row < size; row++) {
for (col = 0 ; col < size; col++) {
int n = matrix[row][col];
System.out.print((n < 10 ) ? (n + " " )
: (n + " " ));
}
System.out.println();
}
}
public static void main(String[] args)
{
int size = 5 ;
printSpiral(size);
}
}
|
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
Time complexity: O(n*n) where n is given size of matrix
Auxiliary space : O(n*n) for 2-d matrix
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
12 Sep, 2022
Like Article
Save Article