Skip to content

Instantly share code, notes, and snippets.

@AmosAidoo
Created March 31, 2020 23:56
Show Gist options
  • Save AmosAidoo/eefff1e682bd3d79ef08b0aa882facd7 to your computer and use it in GitHub Desktop.
Save AmosAidoo/eefff1e682bd3d79ef08b0aa882facd7 to your computer and use it in GitHub Desktop.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n,s,i,j,b,t;
cin >> n;
int arr[n][n]{0};
s = n*n;
t=n;
b = 0;
i = j = 0;
//Build the spiral
while (true) {
//Move right
for (; j < n; j++) {
if (s<=0) break;
arr[i][j] = s--;
}
j--; i++;
//Move down
for (;i < n; i++) {
if (s<=0) break;
arr[i][j] = s--;
}
j--;i--;
//Move left
for (;j >= b; j--) {
if (s<=0) break;
arr[i][j] = s--;
}
b++;j++;i--;
//Move up
for (; i >= b ; i--) {
if (s<=0) break;
arr[i][j] = s--;
}
if (s<=0) break;
n--;i++;s++;
}
//Print the spiral
for (i = 0; i < t; i++) {
for (j = 0; j < t; j++) {
cout << setw(5) << left << arr[i][j];
}
cout << "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment