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> > result;
        for (int i = 0; i < n; i++)
        {
            vector<int> temp(n, 0);
            result.push_back(temp);
        }

        int maxNum = n*n;
        int num = 1;
        int left = 0;
        int right = n-1;
        int top = 0;
        int bottom = n-1;
        while (num <= maxNum)
        {
            int row = top;
            int column = left;
            while (column <= right)
            {
                result[row][column++] = num++;
            }
            top++;
            row++;
            column = right;

            while (row <= bottom)
            {
                result[row++][column] = num++;
            }
            right--;
            column--;
            row = bottom;

            while (column >= left)
            {
                result[row][column--] = num++;
            }
            bottom--;
            row--;
            column = left;

            while (row >= top)
            {
                result[row--][column] = num++;
            }
            left++;
        }

        return result; 
    }
};


你可能感兴趣的:(Spiral Matrix II)