Array
059. Spiral Matrix II
Given a positive integer, generate a square matrix filled with elements from to in spiral order.
就是给定一个,将元素按照顺时针组成一个的矩阵
举个例子
,Output:
Solutions
class Solution:
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
matrix=[[0 for _ in range(n)] for _ in range(n)]
counter = 1
i,j=0,0
top,right,bottom,left=0,n-1,n-1,0
direction = "right"
while counter <= n*n:
matrix[i][j] = (counter)
counter += 1
if direction == "right":
if j+1 <= right:
j += 1
else:
right -= 1
i += 1
direction = "down"
elif direction == "down":
if i+1 <= down:
i += 1
else:
down -= 1
j -= 1
direction = "left"
elif direction == "left":
if j-1 >= left:
j -= 1
else:
left += 1
i -= 1
direction = "up"
else:
if i-1 >= up:
i -= 1
else:
j += 1
up += 1
direction = "right"
return matrix
OR
class Solution(object):
# @return a list of lists of integer
def generateMatrix(self, n):
matrix = [[0 for _ in xrange(n)] for _ in xrange(n)]
left, right, top, bottom, num = 0, n - 1, 0, n - 1, 1
while left <= right and top <= bottom:
for j in xrange(left, right + 1):
matrix[top][j] = num
num += 1
for i in xrange(top + 1, bottom):
matrix[i][right] = num
num += 1
for j in reversed(xrange(left, right + 1)):
if top < bottom:
matrix[bottom][j] = num
num += 1
for i in reversed(xrange(top + 1, bottom)):
if left < right:
matrix[i][left] = num
num += 1
left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
return matrix
网友评论