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 {
public:
    vector<vector<int> > generateMatrix(int n) {
        vector<vector<int> >re;
        for(int i = 0 ;i < n; i++)
        {
            vector <int> temp(n,0);
            re.push_back(temp);
        }
        int direction =0;   //0 right ,1 down ,2 left, 3 up
        int length = n;
        int x = 0;
        int y = 0;
        int step = 0;
        for(int i = 1 ; i <= n*n ; i++)
        {
            re[x][y] = i;
            step++;
            if(step == length)  //should turn
            {
                direction = (direction + 1)%4;
                if(direction == 0)
                {
                    y = y+1;
                    step = 0;
                }
                else if(direction == 1)
                {
                    x = x+1;
                    length--;
                    step = 0;
                }
                else if(direction == 2)
                {
                    y = y-1;
                    step = 0;
                }
                else
                {
                    x = x-1;
                    length--;
                    step = 0;
                }
            }
            else
            {
                if(direction == 0) y = y+1;
                else if(direction == 1)x = x+1;
                else if(direction == 2)y = y-1;
                else x = x-1;
            }
            
        }
        return re;
    }
};

  

原文地址:https://www.cnblogs.com/pengyu2003/p/3595609.html