Python Recursive Solution. Easy-understand.

  • 0

    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)]
        return matrix
    def  generate(self,start,sx,sy,n,matrix):
        if n == 0:
        if n == 1:
            matrix[sx][sy] = start
        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

Log in to reply

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