Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
LeetCode:
// Source : https://oj.leetcode.com/problems/spiral-matrix-ii/
// Author : Chao Zeng
// Date : 2015-1-27
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > matrix(n,vector<int>(n));
int start = 0;
int end = n - 1;
int num = 1;
while (start < end){
for (int i = start; i < end; i++){
matrix[start][i] = num;
num++;
}
for (int i = start; i < end; i++){
matrix[i][end] = num;
num++;
}
for (int i = end; i > start; i--){
matrix[end][i] = num;
num++;
}
for (int i = end; i > start; i--){
matrix[i][start] = num;
num++;
}
start++;
end--;
}
if (start == end){
matrix[start][start] = num;
}
return matrix;
}
};