题目描述:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
解题思路:
1 class Solution { 2 public: 3 vector<vector<int>> generateMatrix(int n) { 4 vector<vector<int>> matrix(n ,vector<int>(n, 0)); 5 if (n == 0) { 6 return matrix; 7 } 8 int left = 0; 9 int right = n - 1; 10 int up = 0; 11 int down = n - 1; 12 13 int count = n * n; 14 int ii = 0; 15 16 while (true) { 17 18 for (int i = left; i <= right; ++i) { 19 matrix[up][i] = ++ii; 20 } 21 if (ii >= count) { 22 break; 23 } 24 25 up += 1; 26 for (int i = up; i <= down; ++i) { 27 matrix[i][right] = ++ii; 28 } 29 if (ii >= count) { 30 break; 31 } 32 33 right -= 1; 34 for (int i = right; i >= left; --i) { 35 matrix[down][i] = ++ii; 36 } 37 if (ii >= count) { 38 break; 39 } 40 41 down -= 1; 42 for (int i = down; i >= up; --i) { 43 matrix[i][left] = ++ii; 44 } 45 left += 1; 46 47 if (ii >= count) { 48 break; 49 } 50 } 51 52 return matrix; 53 } 54 };