Python Recursive Solution. Easy-understand.


  • 0
    A

    Use recursion to solve this problem. In each recursion, place the values on the four edges, then recursively place the matrix inside.

    def  generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        matrix = [[0 for i in xrange(n)] for j in xrange(n)]
        self.generate(1,0,0,n,matrix)
        return matrix
        
    def  generate(self,start,sx,sy,n,matrix):
        if n == 0:
            return
        if n == 1:
            matrix[sx][sy] = start
            return
        for j in xrange(sy,sy+n):
            matrix[sx][j] = start
            start += 1
        for i in xrange(sx+1,sx+n):
            matrix[i][sy+n-1] = start
            start += 1
        for j in xrange(sy+n-2,sy-1,-1):
            matrix[sx+n-1][j] = start
            start += 1
        for i in xrange(sx+n-2,sx,-1):
            matrix[i][sy] = start
            start += 1
        self.generate(start,sx+1,sy+1,n-2,matrix)

Log in to reply
 

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