Python easy to follow solution.


  • 3
    C
    def generateMatrix(self, n):
        if not n:
            return []
        res = [[0 for _ in xrange(n)] for _ in xrange(n)]
        left, right, top, down, num = 0, n-1, 0, n-1, 1
        while left <= right and top <= down:
            for i in xrange(left, right+1):
                res[top][i] = num 
                num += 1
            top += 1
            for i in xrange(top, down+1):
                res[i][right] = num
                num += 1
            right -= 1
            for i in xrange(right, left-1, -1):
                res[down][i] = num
                num += 1
            down -= 1
            for i in xrange(down, top-1, -1):
                res[i][left] = num
                num += 1
            left += 1
        return res

  • 0
    R

    My solution is not so short, but I made it easier to follow with enums:

    class Direction:
            North = 0
            East = 1
            South = 2
            West = 3
    
    class Solution(object): 
    
        def generateMatrix(self, n):
              if n == 0:
                return []
            if n == 1:
                return [[1]]
            fBig = -sys.maxint
            
            a = [ [fBig for _ in xrange(n)] for x in xrange(n)]
            cur = [0,0]
            dir = Direction.East
            for i in xrange(1, (n**2) + 1):
                x = cur[0]
                y = cur[1]
                a[y][x] = i
                if dir == Direction.East:
                    if x + 1 >= n or a[y][x+1] != fBig:
                        dir = Direction.South
                        cur[1] += 1
                    else:
                        cur[0] += 1
                    continue
                if dir == Direction.South:
                    if y + 1 >= n or a[y+1][x] != fBig:
                        dir = Direction.West
                        cur[0] -= 1
                    else:
                        cur[1] += 1
                    continue
                if dir == Direction.West:
                    if x - 1 < 0 or a[y][x-1] != fBig:
                        dir = Direction.North
                        cur[1] -= 1
                    else:
                        cur[0] -= 1
                    continue
                if dir == Direction.North:
                    if y - 1 < 0 or a[y-1][x] != fBig:
                        dir = Direction.East
                        cur[0] += 1
                    else:
                        cur[1] -= 1
                    continue
            return a
    

  • 0
    L

    Could you have used iterable and next() to increment num?


Log in to reply
 

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