剑指offer-顺时针打印矩阵

顺时针打印矩阵

一、问题描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.

二、算法思路

对于这样一个矩阵,顺时针进行打印有一定的规律,可以将矩阵看成是由很多个不同大小的甜甜圈构成。
先打印最外侧的甜甜圈,然后打印第二层的,逐次往内。

三、算法实现

3.1、Python实现版

# -*- coding:utf-8 -*-
class Solution:
    # matrix类型为二维列表,需要返回列表
    def printMatrix(self, matrix):
        # write code here
        # 最外面的一圈
        res = []
        # row是列表的最大行下标
        row = len(matrix) - 1
        # col是列表的最大列下标
        col = len(matrix[0]) - 1
        # i是初始行,j是初始列
        i = 0
        j = 0
        while i <= row and j <= col:  # 每次循环都顺时针打印最外面的一圈
            res += matrix[i][j:col + 1]  # 把外圈的第一行打印
            print('1:'+str(matrix[i][j:col + 1]))
            if i+1<row:
                temp=[m[col] for m in matrix][i+1:row]
                print('2:' + str(temp))
                res += temp
            if i!=row:
                if j==0:
                    res += matrix[row][col::-1]
                    print("3:"+str(matrix[row][col::-1]))
                else:  # i>0
                    res += matrix[row][col:j-1:-1]
            if j!=col:
                if row-1>i:
                    temp=[m[j] for m in matrix][row-1:i:-1]
                    res += temp
                    print("4:"+str(temp))
            # 改变下标
            i = i + 1
            j = j + 1
            col = col - 1
            row = row - 1
            pass
        return res

3.2、大佬的Python代码

    def printMatrix(self, matrix):
        res = []
        while matrix:
            res += matrix.pop(0)
            if matrix and matrix[0]:
                for row in matrix:
                    res.append(row.pop())
            if matrix:
                res += matrix.pop()[::-1]
            if matrix and matrix[0]:
                for row in matrix[::-1]:
                    res.append(row.pop(0))
        return res
posted @ 2019-02-24 10:45  MarkKobs  阅读(244)  评论(0编辑  收藏  举报