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 ] ]
Solution: Simulation
Time complexity: O(n^2)
Space complexity: O(n^2)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// Author: Huahua class Solution { public: vector<vector<int> > generateMatrix(int n) { vector<vector<int>> ans(n, vector<int>(n)); int dir = 2, x = 0, y = 0; int max_x = n - 1, max_y = n - 1; int min_x = 0, min_y = 1; int i = 0; while (++i <= n*n) { ans[y][x] = i; switch (dir) { // up case 1: if (--y == min_y) { dir = 2; ++min_y; } break; // right case 2: if (++x == max_x) { dir = 3; --max_x; } break; // down case 3: if (++y == max_y) { dir = 4; --max_y; } break; // left case 4: if (--x == min_x) { dir = 1; ++min_x; } break; } } return ans; } }; |