[编程题]顺时针打印矩阵

顺时针打印矩阵

http://www.nowcoder.com/questionTerminal/9b4c81a02cd34f76be2659fa0d54342a

# -*- coding:utf-8 -*-
class Solution:
    # matrix类型为二维列表,需要返回列表

    def printRec(self, matrix, x1, y1, x2, y2):
        if x1 > x2 or y1 > y2:
            return

        if x1 == x2:
            for i in range(y1, y2+1):
                self.res.append(matrix[i][x1])
            return

        if y1 == y2:
            for i in range(x1, x2+1):
                self.res.append(matrix[y1][i])
            return

        for i in range(x1, x2):
            self.res.append(matrix[y1][i])

        for i in range(y1, y2):
            self.res.append(matrix[i][x2])

        for i in range(x2, x1, -1):
            self.res.append(matrix[y2][i])

        for i in range(y2, y1, -1):
            self.res.append(matrix[i][x1])

    def printMatrix(self, matrix):
        x1 = 0
        y1 = 0
        self.res = []
        x2 = len(matrix[0]) - 1
        y2 = len(matrix) - 1

        while x1 <= x2 and y1 <= y2:
            self.printRec(matrix, x1, y1, x2, y2)
            x1 += 1
            x2 -= 1
            y1 += 1
            y2 -= 1
        return self.res
全部评论

相关推荐

我已成为0offer的糕手:别惯着,胆子都是练出来的,这里认怂了,那以后被裁应届被拖工资还敢抗争?
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务