Skip to content

Instantly share code, notes, and snippets.

@gallirohik
Created August 1, 2018 11:09
Show Gist options
  • Save gallirohik/3d81a50d5a6f68f7912fde4a00c366e1 to your computer and use it in GitHub Desktop.
Save gallirohik/3d81a50d5a6f68f7912fde4a00c366e1 to your computer and use it in GitHub Desktop.
spiral
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void print(vector<vector<int>>mat )
{
int n=mat.size();
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<mat[i][j]<<" ";
}
cout<<endl;
}
}
void printPattern(int n)
{
vector< vector<int> >vect(n,vector<int>(n,0));
int c=1;
int i,j,k,l;
int sci=0,sri=0,eci=n-1,eri=n-1;
while(n*n>=c)
{
for(i=sci;(i<=eci)&&(vect[sri][i]==0);i++)
{
vect[sri][i]=c;
c++;
}
for(j=sri+1;(j<=eri)&&(vect[j][eci]==0);j++)
{
vect[j][eci]=c;
c++;
}
for(k=eci-1;(k>=sci)&&(vect[eri][k]==0);k--)
{
vect[eri][k]=c;
c++;
}
for(l=eri-1;(l>=sri+1)&&(vect[l][sci]==0);l--)
{
vect[l][sci]=c;
c++;
}
sri++;
sci++;
eri--;
eci--;
}
print(vect);
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
cin>>n;
printPattern(n);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment