59. Spiral Matrix II

These two problems are generally the same:

class Solution {
public:
enum class Direction {
left,
right,
up,
down
};
vector<vector<int>> generateMatrix(int n) {
const auto size = n * n;

vector<vector<int>> result(n, std::vector<int>(n));

int i = 0;
int j = 0;
int rowsMin = 0;
int rowsMax = n;
int colsMin = 0;
int colsMax = n;
int cursor = 1;
Direction dir = Direction::right;

while (cursor <= size) {
result[i][j] = cursor;
++cursor;
            switch (dir) {
case Direction::right:
if (j + 1 < colsMax) {
++j;
} else {
++i;
++rowsMin;
dir = Direction::down;
}
break;

case Direction::left:
if (j > colsMin) {
--j;
} else {
--i;
--rowsMax;
dir = Direction::up;
}
break;

case Direction::up:
if (i > rowsMin) {
--i;
} else {
++j;
++colsMin;
dir = Direction::right;
}
break;

case Direction::down:
if (i + 1 < rowsMax) {
++i;
} else {
--j;
--colsMax;
dir = Direction::left;
}
break;
}
}

return result;
}
};