Share my easy-2-understand python iterative solution


  • 0
    D

    The idea is very simple: do it in the order of top, right, bottom and left.

    class Solution:
        # @param {integer} n
        # @return {integer[][]}
        def generateMatrix(self, n):
            # initialize imatrix
            matrix = [[0] * n for _ in range(n)]
            current, end = 1, n*n
            # initialize top/bottom row, left/right column
            topRow, bottomRow, leftColumn, rightColumn = 0, n-1, 0, n-1
            while current <= end:
                # set top row
                matrix[topRow][leftColumn:rightColumn+1] = range(current, current+rightColumn+1-leftColumn)
                current += (rightColumn + 1 - leftColumn)
                # set right column
                for row in range(topRow+1, bottomRow):
                    matrix[row][rightColumn] = current
                    current += 1
                if current > end:
                    break
                # set bottom row
                matrix[bottomRow][leftColumn:rightColumn+1] = range(current+rightColumn-leftColumn, current-1, -1)
                current += (rightColumn + 1 - leftColumn)
                # set left column
                for row in range(bottomRow-1, topRow, -1):
                    matrix[row][leftColumn] = current
                    current += 1
                # update top/bottom row, left/right column
                topRow, bottomRow, leftColumn, rightColumn = topRow+1, bottomRow-1, leftColumn+1, rightColumn-1
    
            return matrix

Log in to reply
 

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