 # Short, elegant, explanatory solution without hard-coded if-else statements

#1
``````#define MOVE_RIGHT 0    //MOVE_DOWN = 1, MOVE_LEFT = 2, MOVE_UP = 3
vector<vector<int> > Solution::generateMatrix(int A) {
int n = A, maxm = n*n;
vector<vector<int>> res(n, vector<int>(n));
vector<int> limits({n-1, n-1, 0, 1});           //rlim, dlim, llim, ulim (movement boundaries)
vector<int> indices({0, 0});                    //{i, j} used for moving in the matrix
int direction = MOVE_RIGHT;                     //starting direction

for(int term = 1; term <= maxm; term++){
res[indices][indices] = term;         //fill the term
int axis = (direction+1) % 2;               //current axis of movement
int increment = 1 - (2 * (direction / 2));  //current increment for current direction
if(indices[axis] == limits[direction]){     //if we have reached the movement boundary
limits[direction] -= increment;         //update limit
direction = (direction+1) % 4;          //update direction
axis = (direction+1) % 2;               //new axis for the updated direction
increment = 1 - (2 * (direction / 2));  //new increment for updated direction
indices[axis] += increment;             //move in updated direction
}
else                                        //ok to continue moving
indices[axis] += increment;
}
return res;
}``````