【leetcode】Spiral Matrix II

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:

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

与Spiral Matrix相似,给定方阵的维度n,返回一个螺旋矩阵。

 1 class Solution {
 2 public:
 3     vector<vector<int> > generateMatrix(int n) {
 4         vector< vector<int> > matrix(n, vector<int>(n));
 5         //begin_row is the row number, end_row is the remaind size of each row
 6         int begin_row = 0, end_row = n - 1;
 7         //begin_col is the col number,end_col is the remaind size of each col
 8         int begin_col = 0, end_col = n - 1;
 9 
10         int num = 1;
11         while(true){
12             for(int i = begin_row; i <= end_row; ++i)//left to right
13                 matrix[begin_row][i] = num++;
14             if(++begin_col > end_col) break;
15 
16             for(int i = begin_col; i <= end_col; ++i)//up to down
17                  matrix[i][end_row] = num++;
18             if(begin_row > --end_row) break;
19 
20             for(int i = end_row; i >= begin_row; --i)//right to left
21                 matrix[end_col][i] = num++;
22             if(begin_col > --end_col) break;
23 
24             for(int i = end_col; i >= begin_col; --i)//bottom to up
25                 matrix[i][begin_row] = num++;
26             if(++begin_row > end_row) break;
27         }
28 
29         return matrix;
30     }
31 };
View Code


原文地址:https://www.cnblogs.com/zxy1992/p/4279001.html