A mathematical approach


  • 0
    H
    vector<vector<int>> generateMatrix(int n) {
        int loops = n >> 1, j, cnt = 1;
        vector<vector<int>> m(n, std::vector<int>(n));
    
        for (int i = 0; i < loops; i++){
            for (j = i; j < n - i; j++)
                m[i][j] = cnt++;
            for (j = i + 1; j < n - i; j++)
                m[j][n - i - 1] = cnt++;
            for (j = n - i - 2; j >= i; j--)
                m[n - i - 1][j] = cnt++;
            for (j = n - i - 2; j > i; j--)
                m[j][i] = cnt++;
        }
    
        if (n % 2 == 1) m[loops][loops] = cnt;
        return m;
    }

  • 0
    H

    My way to solve this problem is to divide the spiral into several loops, each loop i is made of 4 lines in order: row i , column (n-i-1), row (n-i-1), and column i. For odd number n, we need to fill n^2 at m[loops][loops].


  • 0
    H
    def generateMatrix(n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        loops = n >> 1; cnt = 1
        m = [[0 for k in range(n)] for k in range(n)]
        for i in xrange(loops):
            for j in xrange(i, n-i):
                m[i][j] = cnt; cnt += 1
            for j in xrange(i+1, n-i ):
                m[j][n-i-1] = cnt; cnt += 1
            for j in xrange(n-i-2, i-1, -1):
                m[n-i-1][j] = cnt; cnt += 1
            for j in xrange(n-i-2, i, -1):
                m[j][i] = cnt; cnt += 1
    
        if n % 2 == 1:
            m[loops][loops] = cnt
    
        return m

Log in to reply
 

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