recursive c++ solution


  • 0
    W

    '''

    void fillMatrix(vector< vector<int> > &v, int start, int size, int num)
    {
        if (size <= 0)
            return;
    
        int upLeft = start; //up left corner
        int upRight = start + size - 1; //up right corner
        int downLeft = upRight + 2*size - 2; // left buttom corner
        int end = downLeft + size - 2; // the end of one circle
        
        // put values from out circle to inner circle
        // start from v[0][0], then start from v[1][1] and so on
        for (int i = num; i < v.size() - num; i++)
        {
            v[num][i] = upLeft++;
            v[i][v.size() - num-1] = upRight++;
            v[v.size() - num-1][i] = downLeft--;
            v[i][num] = (1+end--);
        }
        // reset the v[0][0], v[1][1]
        v[num][num] = start;
        //recursively change the start, the size, and the start index
        fillMatrix(v, end+size+1, size-2, num+1);
        
    }
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> v;
        v.resize(n);
        for (int i =0 ; i < n; i++)
            v[i].resize(n);
            
        fillMatrix(v, 1, n, 0);
        return v;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.