48. 旋转图像
给定一个 n × n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。
你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要 使用另一个矩阵来旋转图像。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[[7,4,1],[8,5,2],[9,6,3]]
示例 2:
输入:matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
输出:[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
示例 3:
输入:matrix = [[1]]
输出:[[1]]
示例 4:
输入:matrix = [[1,2],[3,4]]
输出:[[3,1],[4,2]]
提示:
matrix.length == n
matrix[i].length == n
1 <= n <= 20
-1000 <= matrix[i][j] <= 1000
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n=len(matrix)
for i in range(n-1):
for j in range(i+1,n):
matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j]
for m in range(n):
matrix[m]=list(reversed(matrix[m]))
return matrix
54. 螺旋矩阵
给你一个 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]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m_start=0
n_start=0
m_end=len(matrix)
n_end=len(matrix[0])
length=m_end*n_end
res=[]
next_=[[0,1],[1,0],[0,-1],[-1,0]]
row=0
col=0
now=0
res_count=0
while True:
next_row,next_col=next_[now]
res.append(matrix[row][col])
res_count+=1
if res_count==length:
return res
if m_start<=row+next_row<m_end and n_start<=col+next_col<n_end:
row+=next_row
col+=next_col
else:
if now==0:
m_start+=1
elif now==1:
n_end-=1
elif now==2:
m_end-=1
elif now==3:
n_start+=1
now+=1
now%=4
next_row,next_col=next_[now]
row+=next_row
col+=next_col
498. 对角线遍历
给你一个大小为 m x n 的矩阵 mat ,请以对角线遍历的顺序,用一个数组返回这个矩阵中的所有元素。
示例 1:
输入:mat = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,4,7,5,3,6,8,9]
示例 2:
输入:mat = [[1,2],[3,4]]
输出:[1,2,3,4]
提示:
m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
-105 <= mat[i][j] <= 105
class Solution:
def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
m_start=0
n_start=0
m_end=len(mat)
n_end=len(mat[0])
length=m_end*n_end
next_=[[-1,1],[1,-1]]
row=0
col=0
now=0
res_count=0
res=[]
while True:
next_row,next_col=next_[now]
# print("row and col",row,col)
res.append(mat[row][col])
res_count+=1
if res_count==length:
return res
if m_start<=row+next_row<m_end and n_start<=col+next_col<n_end:
row+=next_row
col+=next_col
else:
if now==0:
next_row=0
next_col=1
# print(col+next_col,n_end)
if not ( m_start<=row+next_row<m_end and n_start<=col+next_col<n_end):
next_row=1
next_col=0
elif now==1:
next_row=1
next_col=0
if not m_start<=row+next_row<m_end and n_start<=col+next_col<n_end:
next_row=0
next_col=1
row+=next_row
col+=next_col
now+=1
now%=2