My solution with python

  • 0
    def get_x_y(self, m, b, x, y, n):
        if b == 0:
            if y < n-1:
                if not m[x][y+1]:
                    return x, y+1, b
            return x+1, y, 1
        if b == 1:
            if x < n-1:
                if not m[x+1][y]:
                    return x+1, y, b
            return x, y-1, 2
        if b == 2:
            if y > 0:
                if not m[x][y-1]:
                    return x, y-1, b
            return x-1, y, 3
        if b == 3:
            if x > 0:
                if not m[x-1][y]:
                    return x-1, y, b
            return x, y+1, 0
    def generateMatrix(self, n):
        x, y, b = 0, -1, 0
        m = [[False]*n for i in range(n)]
        res = [[0]*n for i in range(n)]
        for i in range(1, n*n+1):
            x, y, b = self.get_x_y(m, b, x, y, n)
            res[x][y] = i
            m[x][y] = True
        return res

Log in to reply

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