要求
- 时间限制:1秒
- 空间限制:32768K
- 热度指数:385415
- 本题知识点: 数组
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
思路
思路一:直接旋转打印打印
python实现
# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
li = []
rows = len(matrix)
if rows == 0:
return li
cols = len(matrix[0])
left, right, top, bottom = 0, cols-1, 0, rows-1
while left<=right and top<=bottom:
for i in range(left, right+1):
li.append(matrix[top][i])
for i in range(top+1, bottom+1):
li.append(matrix[i][right])
if bottom > top:
for i in range(right-1, left-1, -1):
li.append(matrix[bottom][i])
if left < right:
for i in range(bottom-1, top, -1):
li.append(matrix[i][left])
left+=1
right-=1
top+=1
bottom-=1
return li
- 运行时间:24ms
- 占用内存:5680k
C++实现
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
int rows = matrix.size();
int cols = matrix[0].size();
vector<int> v;
if (rows==0 || cols==0)
return v;
int left = 0; int top = 0; int right = cols-1; int bottom = rows - 1;
while (left<=right && top<=bottom){
// left to right
for (int i=left; i<=right; i++)
v.push_back(matrix[top][i]);
// top to bottom
for (int i=top+1; i<=bottom; i++)
v.push_back(matrix[i][right]);
// right to left
if (top<bottom)
for (int i=right-1; i>=left; i--)
v.push_back(matrix[bottom][i]);
// bottom to top
if (left<right)
for (int i=bottom-1; i>top; i--)
v.push_back(matrix[i][left]);
left++; top++; right--; bottom--;
}
return v;
}
};
- 运行时间:3ms
- 占用内存:476k
思路二:旋转魔方问题
C++实现
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> v;
int rows = matrix.size();
while (rows != 0){
for (int i=0; i<matrix[0].size(); i++)
v.push_back(matrix[0][i]);
if (rows == 1)
break;
matrix = turn(matrix);
rows = matrix.size();
}
return v;
}
vector<vector<int> > turn(vector<vector<int> > matrix) {
int rows = matrix.size(); int cols = matrix[0].size();
vector<vector<int> > newMat(cols, vector<int>(rows-1));
for (int i=cols-1; i>=0; i--){ // 原矩阵列
for (int j=1; j<rows; j++){ // 原矩阵行
newMat[cols-1-i][j-1] = matrix[i][j];
}
}
return newMat;
}
};