题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
C++实现:
使用left, right, top, bottom分别表示打印一圈的最左边、最右边、最上边和最下边,并且right = left或top = bottom时,打印会出错,具体可以照着程序分析一下;
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
int row = matrix.size();
int col = matrix[0].size();
vector<int> res;
int left = 0, right = col - 1, top = 0, bottom = row - 1;
while(left <= right && top <= bottom)
{
for(int i = left; i < right + 1; i ++)
res.push_back(matrix[top][i]);
for(int i = top + 1; i < bottom + 1; i ++)
res.push_back(matrix[i][right]);
if((top != bottom) and (left != right))
{
for(int i = right - 1; i >= left; i --)
res.push_back(matrix[bottom][i]);
for(int i = bottom - 1; i >= top + 1; i --)
res.push_back(matrix[i][left]);
}
left = left + 1;
right = right - 1;
top = top + 1;
bottom = bottom - 1;
}
return res;
}
};
python 实现:
思路:每次输出第一行,然后删除第一行,将矩阵再进行逆时针旋转,再输出第一行,依次执行,知道矩阵为空
# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
res = []
while(matrix):
res += matrix.pop(0)
if not matrix or not matrix[0]:
break
matrix[:] = map(list, zip(*matrix))[::-1]
return res