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 ] ]
class Solution { public: vector<vector<int> > generateMatrix(int n) { static int dir[][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; vector<vector<int> > ans(n, vector<int>(n)); int num = 1; int k = 0; int x = -1, y = 0; while (n) { if (k & 1) --n; for (int i=0; i<n; i++) { x += dir[k][0]; y += dir[k][1]; ans[y][x] = num++; } k = (k+1) & 3; } return ans; } };
原文地址:http://blog.csdn.net/elton_xiao/article/details/44702867