1 问题
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
2 答案
这题直接不会
再次尝试修改
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
up = 0
down = len(matrix) - 1
left = 0
right = len(matrix[0]) - 1
res = []
curx = 0
cury = 0
move = [(1,0), (0,1), (-1,0), (0,-1)]
add = 0
# 从结果出发,去寻找while的条件比较容易
while len(res) != (len(matrix)) * (len(matrix[0])):
res.append(matrix[cury][curx])
if curx == right and cury == up and add == 0:
up += 1
add += 1
if cury == down and curx == right and add == 1:
right -= 1
add += 1
if curx == left and cury == down and add == 2:
down -= 1
add += 1
if cury == up and curx == left and add == 3:
left += 1
add += 1
add %= 4
curx+=move[add][0]
cury+=move[add][1]
return res
再次尝试
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
add = 0
ma = [(1,0), (0,1), (-1,0), (0,-1)]
res = []
m = len(matrix)
n = len(matrix[0])
x, y = 0, 0
left, right, up, down = 0, n-1, 0, m-1
while len(res) < m*n:
res.append(matrix[y][x])
if add == 0 and x == right:
add+=1
up+=1
elif add == 1 and y == down:
add+=1
right-=1
elif add == 2 and x == left:
add += 1
down-=1
elif add == 3 and y == up:
add+=1
left+=1
add %= 4
x += ma[add][0]
y += ma[add][1]
return res
官方解, 顺时针旋转矩阵:先转置,再上下翻转。逆时针旋转矩阵:先上下翻转,再转置。
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
while matrix:
res += matrix.pop(0) # pop 默认返回最后一个元素
matrix = list(map(list, zip(*matrix)))[::-1] # [::-1] 上下翻转
return res
https://leetcode.cn/problems/spiral-matrix/solutions/24232/na-yi-xing-ni-shi-zhen-zhuan-yi-xia-by-suixin-3/
也可以直接遍历,但要确定好边界,遍历方向等细节问题
class Solution(object):
def spiralOrder(self, matrix):
M, N = len(matrix), len(matrix[0])
left, right, up, down = 0, N - 1, 0, M - 1
res = []
x, y = 0, 0
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
cur_d = 0
while len(res) != M * N:
res.append(matrix[x][y])
if cur_d == 0 and y == right:
cur_d += 1
up += 1
elif cur_d == 1 and x == down:
cur_d += 1
right -= 1
elif cur_d == 2 and y == left:
cur_d += 1
down -= 1
elif cur_d == 3 and x == up:
cur_d += 1
left += 1
cur_d %= 4 # 4个方向,所以是4
x += dirs[cur_d][0]
y += dirs[cur_d][1]
return res
https://leetcode.cn/problems/spiral-matrix/solutions/656925/ju-zhen-bian-li-wen-ti-de-si-bu-qu-by-fu-91za/