Skip to content

Instantly share code, notes, and snippets.

@jenglamlow
Last active January 8, 2020 14:47
Show Gist options
  • Select an option

  • Save jenglamlow/476556736438b4daa331d2c2b344bd35 to your computer and use it in GitHub Desktop.

Select an option

Save jenglamlow/476556736438b4daa331d2c2b344bd35 to your computer and use it in GitHub Desktop.
Write a traverse(int N) function to traverse a perfect square with size N from middle of the square and spiral counterclockwise until it reach to the bottommost right
#include <iostream>
using namespace std;
void traverse(int* arr,int N)
{
int i = (N-1)/2;
int j = i;
int steps(1);
int maxSteps = N;
cout << arr[j*N + i] << " ";
while (steps < maxSteps) {
// odd
if (steps % 2 != 0) {
// right
for(int a=0; a<steps; a++) {
++i;
cout << arr[j*N + i] << " ";
}
// up
for(int a=0; a<steps; a++) {
--j;
cout << arr[j*N + i] << " ";
}
} else {
// left
for(int a=0; a<steps; a++) {
--i;
cout << arr[j*N + i] << " ";
}
// down
for(int a=0; a<steps; a++) {
++j;
cout << arr[j*N + i] << " ";
}
}
steps++;
}
// Last right
for(int a=0; a<steps-1; a++) {
++i;
cout << arr[j*N + i] << " ";
}
cout << endl;
}
int main()
{
int arr1[9] = {1,2,3,4,5,6,7,8,9};
int arr2[25] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25};
traverse(&arr1[0], 3);
traverse(&arr2[0], 5);
// traverse(7);
}
#include <iostream>
using namespace std;
void traverse(int N)
{
int i = (N-1)/2;
int j = i;
int dir(0); // counter to keep track on direction
int counter(0); // counter
int steps(1); // number of steps needed per direction
int totalSteps = N*N; // total number of travese steps
while (counter < totalSteps) {
cout << i << "," << j << " ";
++counter;
// Use direction counter to determine the direction
switch (dir % 4) {
case 0:
++i;
break;
case 1:
++j;
// Increase the steps need for the next pivot direction
if (counter % steps == 0)
++steps;
break;
case 2:
--i;
break;
case 3:
--j;
// Increase the steps need for the next pivot direction
if (counter % steps == 0)
++steps;
break;
}
// Only change direction once it reach the number of steps needed per direction
if (counter % steps == 0)
++dir;
}
cout << endl;
}
int main()
{
traverse(3);
traverse(5);
traverse(7);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment