Skip to content

Instantly share code, notes, and snippets.

@lvv
Last active November 30, 2016 21:54
Show Gist options
  • Save lvv/141008ce9d50f23e291daaff119fb8ef to your computer and use it in GitHub Desktop.
Save lvv/141008ce9d50f23e291daaff119fb8ef to your computer and use it in GitHub Desktop.
spiral matrix
#include <iostream>
#include <vector>
using namespace std;
int main() {
size_t n,m;
std::cin >> n >> m;
vector<vector<int> > M(m, vector<int>(n,-1));
int T=0,B=m,L=0,R=n; // top, bottom, left, right
size_t cnt=1;
int i = L;
int j = T;
while (true) {
if (T >= B) break;
if (L >= R) break;
// top
for (; i<R ; ++i) M[j][i]=cnt++;
--i;
++T;
++j;
if (T >= B) break;
// right
for (; j<B; ++j) M[j][i]=cnt++;
--j;
--R;
--i;
if (L >= R) break;
// bottom
for (; L<=i ; --i) M[j][i]=cnt++;
++i;
--B;
--j;
if (T >= B) break;
// left
for (; T <= j; --j) M[j][i]=cnt++;
++j;
++L;
++i;
if (L >= R) break;
}
// print M
for(size_t j=0; j<m; ++j) {
for(size_t i=0; i<n; ++i) {
cout << M[j][i] << '\t';
}
cout << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment