Spiral Matrix II

描述

Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.

For example,Given n = 3,

You should return the following matrix:

  1. [
  2. [ 1, 2, 3 ],
  3. [ 8, 9, 4 ],
  4. [ 7, 6, 5 ]
  5. ]

分析

这题比上一题要简单。

代码1

  1. // Spiral Matrix II
  2. // 时间复杂度O(n^2),空间复杂度O(n^2)
  3. class Solution {
  4. public:
  5. vector > generateMatrix(int n) {
  6. vector > matrix(n, vector(n));
  7. int begin = 0, end = n - 1;
  8. int num = 1;
  9. while (begin < end) {
  10. for (int j = begin; j < end; ++j) matrix[begin][j] = num++;
  11. for (int i = begin; i < end; ++i) matrix[i][end] = num++;
  12. for (int j = end; j > begin; --j) matrix[end][j] = num++;
  13. for (int i = end; i > begin; --i) matrix[i][begin] = num++;
  14. ++begin;
  15. --end;
  16. }
  17. if (begin == end) matrix[begin][begin] = num;
  18. return matrix;
  19. }
  20. };

代码2

  1. // LeetCode, Spiral Matrix II
  2. // @author 龚陆安 (http://weibo.com/luangong)
  3. // 时间复杂度O(n^2),空间复杂度O(n^2)
  4. class Solution {
  5. public:
  6. vector<vector<int> > generateMatrix(int n) {
  7. vector< vector<int> > matrix(n, vector<int>(n));
  8. if (n == 0) return matrix;
  9. int beginX = 0, endX = n - 1;
  10. int beginY = 0, endY = n - 1;
  11. int num = 1;
  12. while (true) {
  13. for (int j = beginX; j <= endX; ++j) matrix[beginY][j] = num++;
  14. if (++beginY > endY) break;
  15. for (int i = beginY; i <= endY; ++i) matrix[i][endX] = num++;
  16. if (beginX > --endX) break;
  17. for (int j = endX; j >= beginX; --j) matrix[endY][j] = num++;
  18. if (beginY > --endY) break;
  19. for (int i = endY; i >= beginY; --i) matrix[i][beginX] = num++;
  20. if (++beginX > endX) break;
  21. }
  22. return matrix;
  23. }
  24. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/simulation/spiral-matrix-ii.html