Skip to content

Instantly share code, notes, and snippets.

@aryamanarora
Created September 8, 2018 03:20
Show Gist options
  • Select an option

  • Save aryamanarora/7a940fe91e0baa9b2fb5cdffb3aa618e to your computer and use it in GitHub Desktop.

Select an option

Save aryamanarora/7a940fe91e0baa9b2fb5cdffb3aa618e to your computer and use it in GitHub Desktop.
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
vector<vector<int>> m(n, vector<int>(n, 0));
m[0][0] = 1;
int x = 0, y = 1;
string dir = "down";
while (m[y][x] == 0) {
if (dir == "down") {
m[y][x] = m[y-1][x] + 1;
if (y == n - 1 or m[y+1][x] != 0) {
x++;
dir = "right";
}
else y++;
}
else if (dir == "right") {
m[y][x] = m[y][x-1] + 1;
if (x == n - 1 or m[y][x+1] != 0) {
y--;
dir = "up";
}
else x++;
}
else if (dir == "up") {
m[y][x] = m[y+1][x] + 1;
if (y == 0 or m[y-1][x] != 0) {
x--;
dir = "left";
}
else y--;
}
else {
m[y][x] = m[y][x+1] + 1;
if (x == 0 or m[y][x-1] != 0) {
y++;
dir = "down";
}
else x--;
}
}
for (auto &x : m) {
for (auto &y : x) cout << y << " ";
cout << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment