[LeetCode] 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;
        if(n == 0)  return result;
        result.resize(n);
        for(int i = 0; i < n; i++)
            result[i].resize(n);
        int col_beg = 0, col_end = n-1;
        int row_beg = 0, row_end = n-1;
        int data = 1;
        while(1)
        {
            for(int col = col_beg; col <= col_end; ++col)
                result[row_beg][col] = data++;
            ++row_beg;
            if(data > n*n)  break;
            for(int row  = row_beg; row <= row_end; ++row)
                result[row][col_end] = data++;
            --col_end;
            if(data > n*n)  break;
            for(int col = col_end; col >= col_beg; --col)
                result[row_end][col] = data++;
            --row_end;
            if(data > n*n)  break;
            for(int row = row_end; row >= row_beg; --row)
                result[row][col_beg] = data++;
            ++col_beg;
            if(data > n*n)  break;
        }
        return result;
    }
};


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