技术交流可以加:
本人微信:xcg852390212
本人qq:852390212
学习交流qq群1(已满): 962535112
学习交流qq群2: 780902027
螺旋矩阵
给定一个包含 m x n
个元素的矩阵(m
行, n
列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
解答
要求对矩阵顺时针打印,可以分解问题,子问题是对矩阵每层进行顺时针打印。处理子问题知道矩阵每层左上角元素(x1,y1)
和右下角元素(x2,y2)
的位置即可。
注意:打印的几种特殊情况
(x1,y1)
和(x2,y2)
在同一行(x1,y1)
和(x2,y2)
在同一列(x1,y1)
和(x2,y2)
是同一个元素
- 时间复杂度:O(mn)
- 空间复杂度:O(mn)
C++代码
class Solution {
public:
void solution(int x1,int y1,int x2,int y2,vector<int>& vec,vector<vector<int>>& matrix)
{
int i=x1,j=y1;
if(x1 < x2 && y1 < y2)
{
for(;j<y2;j++)
{
vec.push_back(matrix[i][j]);
}
for(;i<x2;i++)
{
vec.push_back(matrix[i][j]);
}
for(;j>y1;j--)
{
vec.push_back(matrix[i][j]);
}
for(;i>x1;i--)
{
vec.push_back(matrix[i][j]);
}
}
else if(x1 == x2)
{
for(;j<=y2;j++)
vec.push_back(matrix[i][j]);
}
else if(y1 == y2)
{
for(;i<=x2;i++)
vec.push_back(matrix[i][j]);
}
}
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(matrix.empty())
return vector<int>();
vector<int> res;
int m = matrix.size();
int n = matrix[0].size();
int x1 = 0,y1 = 0;
int x2 = m-1,y2 = n-1;
while(x1<=x2 && y1<=y2)
{
solution(x1++,y1++,x2--,y2--,res,matrix);
}
return res;
}
};
Python代码
class Solution:
def solution(self,x1,y1,x2,y2,vec:List[int],matrix:List[List[int]]):
i = x1
j = y1
if x1 < x2 and y1 < y2:
while j < y2:
vec.append(matrix[i][j])
j += 1
while i < x2:
vec.append(matrix[i][j])
i += 1
while j > y1:
vec.append(matrix[i][j])
j -= 1
while i > x1:
vec.append(matrix[i][j])
i -= 1
elif x1 == x2:
while j <= y2:
vec.append(matrix[i][j])
j += 1
else:
while i <= x2:
vec.append(matrix[i][j])
i += 1
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if len(matrix) == 0:
return matrix
res = list()
m = len(matrix)
n = len(matrix[0])
x1 = 0
y1 = 0
x2 = m-1
y2 = n-1
while x1 <= x2 and y1 <= y2:
self.solution(x1,y1,x2,y2,res,matrix)
x1 += 1
y1 += 1
x2 -= 1
y2 -= 1
return res