Print n x n spiral matrix using O ( 1 ) extra space | C ++ program to print a n x n spiral matrix in clockwise direction using O ( 1 ) space ; Prints spiral matrix of size n x n containing numbers from 1 to n x n ; x stores the layer in which ( i , j ) th element lies ; Finds minimum of four inputs ; For upper right half ; for lower left half ; Driver code ; print a n x n spiral matrix in O ( 1 ) space
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printSpiral ( int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { int x ; x = min ( min ( i , j ) , min ( n - 1 - i , n - 1 - j ) ) ; if ( i <= j ) printf ( " % d TABSYMBOL ▁ " , ( n - 2 * x ) * ( n - 2 * x ) - ( i - x ) - ( j - x ) ) ; else printf ( " % d TABSYMBOL ▁ " , ( n - 2 * x - 2 ) * ( n - 2 * x - 2 ) + ( i - x ) + ( j - x ) ) ; } printf ( " STRNEWLINE " ) ; } } int main ( ) { int n = 5 ; printSpiral ( n ) ; return 0 ; }