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 ] ]
给定整数n, 将1,2,3...nxn个数按螺旋旋转的方式填入nxn的矩阵
同Spiral Matrix, 从外圈到内圈依次填写
class Solution { public: void generate(vector<vector<int> >&matrix, int i, int j, int len, int num){ //i, j 当前圈左上角的坐标 //len 当前圈的边长 //num 将填入当前圈的第一个数值 if(len<1)return; if(len==1){ matrix[i][j]=num; return; } //填写上面的边 int x=i, y=j; while(y<j+len-1){ matrix[x][y++]=num++; } //填写后面的边 while(x<i+len-1){ matrix[x++][y]=num++; } //填写下面的边 while(y>j){ matrix[x][y--]=num++; } //填写左面的边 while(x>i){ matrix[x--][y]=num++; } //填写内圈 generate(matrix, i+1, j+1, len-2, num); } vector<vector<int> > generateMatrix(int n) { vector<vector<int> >result(n, vector<int>(n, 0)); generate(result, 0, 0, n, 1); return result; } };
LeetCode: Spiral Matrix II [058],布布扣,bubuko.com
LeetCode: Spiral Matrix II [058]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/26814291