LeetCode Spiral Matrix II
class Solution { public: vector<vector<int> > generateMatrix(int n) { vector<vector<int> > matrix; if (n < 1) return matrix; for (int i=0; i<n; i++) { matrix.push_back(vector<int>(n, 0)); } int left = 0, top = 0, right = n - 1, bottom = n - 1; int last = 1; while (left <= right && top <= bottom) { last = circle_walk(last, left, top, right, bottom, matrix); left++, top++, bottom--, right--; } return matrix; } int circle_walk(int start, int left, int top, int right, int bottom, vector<vector<int> >& map) { int rows = 0; if (map.size() < 1 || map[0].size() < 1) return start; // top row for (int i=left; i<=right; i++) { map[top][i] = start++; } // right col for (int i=top+1; i<=bottom; i++) { map[i][right] = start++; } // bottom row for (int i=right-1; bottom != top && i>=left; i--) { map[bottom][i] = start++; } // left col for (int i=bottom-1; left != right && i>top; i--) { map[i][left] = start++; } return start; } };
再水一发
第二轮:
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 6 if (n < 1) { 7 return matrix; 8 } 9 10 int xn = n; 11 int yn = n; 12 13 int col = -1; 14 int row = 0; 15 16 int seq = 1; 17 18 while (true) { 19 for (int i=0; i<xn; i++) matrix[row][++col] = seq++; 20 if (--yn == 0) break; 21 22 for (int i=0; i<yn; i++) matrix[++row][col] = seq++; 23 if (--xn == 0) break; 24 25 for (int i=0; i<xn; i++) matrix[row][--col] = seq++; 26 if (--yn == 0) break; 27 28 for (int i=0; i<yn; i++) matrix[--row][col] = seq++; 29 if (--xn == 0) break; 30 } 31 32 return matrix; 33 } 34 };