/// Problem statement: Fill a W X H matrix in spiral fashion outside to inside clockwise
/// For ex: 4 X 6 matrix would look like
/// 1 2 3 4
/// 16 17 18 5
/// 15 24 19 6
/// 14 23 20 7
/// 13 22 21 8
/// 12 11 10 9
///
/// Solution: Prepare a vector<int> of size w x h and fill
/// it in circular fashion as given in problem statement
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
int main(int argc, char *const *argv) {
int w = 3, h = 3;
if(argc != 3) {
cout << "Bad arguments" << endl;
} else {
w = atoi(argv[1]);
h = atoi(argv[2]);
}
#define mat(X,Y) vmat[X+Y*w]
vector<int> vmat(w*h);
int num = 0;
const int mx = w * h;
if(w < 0 || mx < 0) return -3;
int off = 0, wLimit = w - 1, hLimit = h - 1;
#define SET(X,Y) do { if(!mat(X,Y)) mat(X,Y) = ++num; } while(false)
//#define SET(X,Y) do { if(!mat(X,Y)) mat(X,Y) = ++num; cout << '(' << X << ',' << Y << ')' << num << endl; } while(false)
while( (wLimit - off) > 0 && (hLimit - off) > 0) {
for(int i = off; i < wLimit; ++i) SET(i,off);
for(int i = off; i < hLimit; ++i) SET(wLimit,i);
for(int i = wLimit; i > off; --i) SET(i,hLimit);
for(int i = hLimit; i > off; --i) SET(off,i);
++off, --wLimit, --hLimit;
}
if(wLimit == off) {
for(int i = off; i <= hLimit; ++i) SET(off, i);
}
if(hLimit == off) {
for(int i = off; i <= wLimit; ++i) SET(i, off);
}
//assert(num == w * h);
for(int j = 0; j < h; ++j) {
for(int i = 0; i < w; ++i) {
cout << mat(i,j) << '\t';
}
cout << endl;
}
}
// EOF