59. Spiral Matrix II
题目
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 ]]
解析
class Solution_59 {public: vector > generateMatrix(int n) { vector > vecs(n, vector (n,1)); int x0 = 0, y0 = 0; int x1 = n - 1, y1 = n - 1; int index = 0; while (x0<=x1&&y0<=y1) { for (int i = y0; i <= y1;i++) { vecs[x0][i] = ++index; } for (int i = x0 + 1; i <= x1;i++) { vecs[i][y1] = ++index; } for (int i = y1 - 1; i >= y0;i--) { vecs[x1][i] = ++index; } for (int i = x1 - 1; i > x0;i--) { vecs[i][y0] = ++index; } x0++, y0++; x1--, y1--; } return vecs; }};
题目来源