Spiral Matrix II @ LeetCode (Python)
kitt
posted @ 2014年3月22日 19:01
in LeetCode
, 1997 阅读
使用0,1,2,3四个值表示方向以便切换, 用maxUp, maxDown, maxLeft, maxRight四个变量记录四个边界。当 curr >= n * n 就结束。
0,1,2,3 four values are used to indicates direction, maxUp, maxDown, maxLeft, maxRight four variables are used to record four boundaries. When curr >= n * n program can return.
class Solution: # @return a list of lists of integer def generateMatrix(self, n): direct = 0 # 0 go right, 1 go down, 2 go left, 3 go up maxUp = maxLeft = 0 maxDown = maxRight = n - 1 A = [ [0 for j in xrange(n)] for i in xrange(n) ] curr = 0 while True: if direct == 0: # go right for i in xrange(maxLeft, maxRight + 1): curr += 1; A[maxUp][i] = curr maxUp += 1 elif direct == 1: # go down for i in xrange(maxUp, maxDown + 1): curr += 1; A[i][maxRight] = curr maxRight -= 1 elif direct == 2: # go left for i in reversed(xrange(maxLeft, maxRight + 1)): curr += 1; A[maxDown][i] = curr maxDown -= 1 else: # go up for i in reversed(xrange(maxUp, maxDown + 1)): curr += 1; A[i][maxLeft] = curr maxLeft += 1 if curr >= n * n: return A direct = (direct + 1) % 4