题目描述:
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 ] ]
思路分析:四个for循环分别控制四个方向上数字的填入。
代码:
vector<vector<int> > Solution::generateMatrix(int n) { vector<vector<int> > matrix; vector<int> line; int i,j,k; int count = 1; for(i = 0;i < n;i++) { for(j = 0;j < n;j++) line.push_back(0); matrix.push_back(line); line.clear(); } for(i = 0;i*2 < n;i++) { for(j = i,k = i;k < n - i - 1;k++) matrix[j][k] = count++; for(j = i,k = n - 1 - i;j < n - i - 1;j++) matrix[j][k] = count++; for(j = n - i - 1,k = n - i - 1;k > i;k--) matrix[j][k] = count++; for(j = n - 1 - i,k = i;j > i;j--) matrix[j][k] = count++; } if(n % 2 == 1) matrix[n/2][n/2] = count++; return matrix; }
原文地址:http://blog.csdn.net/yao_wust/article/details/42169519