Tuesday, April 22, 2014

[LeetCode] Spiral Matrix II

Problem Statement (link):
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 ]
]
Analysis:
This problem is exactly the opposite of Spiral Matrix I, where we peel off the matrix layer by layer. Here, we need to construct the matrix following the same spiral traverse. We use recursion to add layers to matrix from outer layer to inner layers.

The complexity of the algorithm is O(n^2), where n is the given number - largest edge length.

Code:
class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        vector<vector<int> > mat;
        if (n==0) return mat;
        // construct the matrix
        for (int i=0; i<n; i++)
            mat.push_back(vector<int> (n));
        recur(mat, 1, 0, n);
        return mat;
    }

    // start - start int value of current recursion
    // rec - current number of recursions
    void recur(vector<vector<int> >& mat, int val, int rec, int n) {
        if (val>pow(n,2)) return;
        int l=n-2*rec; // current edge length

        for (int i=rec; i<l+rec; i++)
            mat[rec][i]=val++;
        for (int i=rec+1; i<l+rec; i++)
            mat[i][l+rec-1]=val++;
        for (int i=l+rec-2; i>=rec; i--)
            mat[l+rec-1][i]=val++;
        for (int i=l+rec-2; i>rec; i--)
            mat[i][rec]=val++;

        recur(mat, val, rec+1, n);
    }
};

No comments:

Post a Comment