Simple, slow but very readable Python solution.


  • 1
    P

    This isn't a clever solution. It's slow but very intuitive. My aim was to get something to work first and then optimize later. If anyone has any suggestions on optimizing or cleaning this up (while preserving the readability) please comment :P

    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        matrix = [[0]*n for _ in range(n)]
        elems = iter(range(1, n**2+1))
        for i in range(n//2 + 1):
            for j in range(i, n-i):
                matrix[i][j] = next(elems)
            for j in range(i+1, n-i):
                matrix[j][n-i-1] = next(elems)
            for j in range(i+1, n-i):
                matrix[n-i-1][n-j-1] = next(elems)
            for j in range(i+1, n-i-1):
                matrix[n-j-1][i] = next(elems)
        return matrix
    

Log in to reply
 

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