class Solution: # @return a list of lists of integer def generateMatrix(self, n): rst=[[0 for i in range(n)] for j in range(n)] up=0 down=n-1 left=0 right=n-1 elem=1 while up<=down and left<=right: for i in range(left,right+1): rst[up][i]=elem elem+=1 up+=1 if up<=down: for i in range(up,down+1): rst[i][right]=elem elem+=1 right-=1 else: break if left<=right: for i in reversed(range(left,right+1)): rst[down][i]=elem elem+=1 down-=1 else: break if down>=up: for i in reversed(range(up,down+1)): rst[i][left]=elem elem+=1 left+=1 else: break return rst
Tuesday, September 9, 2014
Leetcode: Spiral Matrix II @Python
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment