Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
AC code:
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> ans(n, vector<int>(n, 0)); int top = 0, bottom = n-1; int left = 0, right = n-1; int num = 1; while (top <= bottom && left <= right) { // left -> right for (int i = left; i <= right; ++i) { ans[top][i] = num++; } top++; // top -> bottom for (int i = top; i <= bottom; ++i) { ans[i][right] = num++; } right--; // right -> left for (int i = right; i >= left; --i) { ans[bottom][i] = num++; } bottom--; // bottom -> top for (int i = bottom; i >= top; --i) { ans[i][left] = num++; } left++; } return ans; } };
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Spiral Matrix II.