题目:
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 ] ]
CPP:
class Solution { public: vector<vector<int>> generateMatrix(int x) { vector<vector<int>> result; if (x == 0) { return result; } else { vector<int> v(x); for (int i = 0; i < x; i++) { result.push_back(v); } } int r = 0; //第几圈 int i; //left to right int a = 1; while (r < x / 2) { for (i = r; i < x - r; i++) { result[r][i] = a; a++; } //up to down for (i = r + 1; i < x - r ; i++) { result[i][x - r-1] = a; a++; } //right to left for (i = x - r - 2; i >= r; i--) { result[x - r-1][i] = a; a++; } //down to up for (i = x - r - 2; i > r; i--) { result[i][r] = a; a++; } r++; } if(2*r !=x) { result[r][r] = a; } return result; } };
python:
class Solution(object): def generateMatrix(self,n): ans = [] for x in range(n): ans.append([0]*n) mini,minj,maxi,maxj = 0,0,n-1,n-1 num = 1 while maxi >= mini and maxj >= minj: #left to right for j in range(minj,maxj+1): ans[minj][j] = num num +=1 mini += 1 #up to down for i in range(mini,maxi+1): ans[i][maxj] = num num +=1 maxj -= 1 #right to left for j in range(maxj,minj-1,-1): ans[maxi][j] = num num +=1 maxi -=1 #down to up for i in range(maxi,mini-1,-1): ans[i][minj] = num num +=1 minj += 1 return ans;