LeetCode59 Spiral Matrix II
题目:
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: (Medium)
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
分析:
跟 Sprial Matrix I处理方式一样,先建立好n * n的数组,然后按照顺时针顺序填入数字即可。
代码:
1 class Solution { 2 public: 3 vector<vector<int>> generateMatrix(int n) { 4 vector<vector<int>> result(n, vector<int>(n,0)); 5 int rowBegin = 0, rowEnd = n - 1, colBegin = 0, colEnd = n - 1; 6 int count = 1; 7 while (rowBegin <= rowEnd && colBegin <= colEnd) { 8 for (int i = colBegin; i <= colEnd; ++i ) { 9 result[rowBegin][i] = count; 10 count++; 11 } 12 rowBegin++; 13 if (rowBegin > rowEnd) { 14 break; 15 } 16 for (int i = rowBegin; i <= rowEnd; ++i) { 17 result[i][colEnd] = count; 18 count++; 19 } 20 colEnd--; 21 if (colBegin > colEnd) { 22 break; 23 } 24 for (int i = colEnd; i >= colBegin; --i) { 25 result[rowEnd][i] = count; 26 count++; 27 } 28 rowEnd--; 29 if (rowBegin > rowEnd) { 30 break; 31 } 32 for (int i = rowEnd; i>= rowBegin; --i) { 33 result[i][colBegin] = count; 34 count++; 35 } 36 colBegin++; 37 } 38 return result; 39 } 40 };