054 Spiral Matrix 旋转打印矩阵

时间:2021-06-28 07:58:09

给出一个 m x n 的矩阵(m 行, n 列),请按照顺时针螺旋顺序返回元素。
例如,给出以下矩阵:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
应该返回 [1,2,3,6,9,8,7,4,5]。
详见:https://leetcode.com/problems/spiral-matrix/description/

Java实现:

class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res=new ArrayList<Integer>();
if(matrix==null||matrix.length==0){
return res;
}
int row=matrix.length;
int col=matrix[0].length; int top=0;
int bottom=row-1;
int left=0;
int right=col-1;
while(top<=bottom&&left<=right){
for(int j=left;j<=right;++j){
res.add(matrix[top][j]);
}
++top;
for(int i=top;i<=bottom;++i){
res.add(matrix[i][right]);
}
--right;
if(top<=bottom){
for(int j=right;j>=left;--j){
res.add(matrix[bottom][j]);
}
}
--bottom;
if(left<=right){
for(int i=bottom;i>=top;--i){
res.add(matrix[i][left]);
}
}
++left;
}
return res;
}
}

C++实现:

class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.empty())
return res; int row = matrix.size();
int col = matrix[0].size(); int top = 0;
int bottom = row - 1;
int left = 0;
int right = col - 1; //螺旋曲线,运动轨迹总是一致的
while (top <= bottom && left <= right)
{
//向右列递增遍历
for (int j = left; j <= right; j++)
{
res.push_back(matrix[top][j]);
}
top++; //遍历后,去掉此行 //向下行递增遍历
for (int i = top; i <= bottom; i++)
{
res.push_back(matrix[i][right]);
}
right--; //遍历后,去掉此列 if (top <= bottom) //重要判断,防止重复
{
//向左列递减遍历
for (int j = right; j >= left; j--)
{
res.push_back(matrix[bottom][j]);
} }
bottom--; //遍历后,去掉此行 if (left <= right) //重要判断,防止重复
{
//向上行递减遍历
for (int i = bottom; i >= top; i--)
{
res.push_back(matrix[i][left]);
}
}
left++; //遍历后,去掉此列
} return res;
}
};