Monday, November 25, 2013

LeetCode Problem : Spiral Matrix II

Problem


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 ]
]

Code


vector<vector<int> > generateMatrix(int n) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    vector<vector<int> > M(n,vector<int>(n,0));
    int i = 0,base = 1;
    int row,col;
    while(i < n/2){
        row = i;
        for(col = i; col < n - 1 - i; ++col)
            M[row][col] = base++;
        col = n - 1 - i;
        for(row = i; row < n - 1 - i; ++row)
            M[row][col] = base++;
        row = n - 1 - i;
        for(col = n - 1 - i; col > i; --col)
            M[row][col] = base++;
        col = i;
        for(row = n - 1 - i; row > i; --row)
            M[row][col] = base++;
        ++i;
    }
    if(n%2 == 1)
        M[n/2][n/2] = base;
    return M;
}

No comments:

Post a Comment