Leetcode-Sprial Matrix II

来源:互联网 发布:高仿mcm怎么在淘宝买 编辑:程序博客网 时间:2024/05/22 00:40

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 {public:    vector<vector<int>> generateMatrix(int n) {        vector<vector<int>> res(n,vector<int>(n));        int count=1,i=0;        while(count<=n*n){            int j=i;            while(j<n-i)                res[i][j++]=count++;   //left to right            j=i+1;            while(j<n-i)                res[j++][n-i-1]=count++;            j=n-i-2;            while(j>i)                res[n-i-1][j--]=count++;            j=n-i-1;            while(j>i)                res[j--][i]=count++;            i++;        }        return res;    }};