【剑指Offer】顺时针打印矩阵 解题报告(Python)

【剑指Offer】顺时针打印矩阵 解题报告(Python)

标签(空格分隔): 剑指Offer


题目地址:https://www.nowcoder.com/ta/coding-interviews

题目描述:

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵:

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.

解题方法

54. Spiral Matrix一样的题目,方法直白,因此不在多说了。

# -*- coding:utf-8 -*-
class Solution:
    # matrix类型为二维列表,需要返回列表
    def printMatrix(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        if not matrix or not matrix[0]: return []
        m, n = len(matrix), len(matrix[0])
        visited = [[0] * n for _ in range(m)]
        res = []
        self.row, self.col = 0, 0
        def spiral():
            move = False
            while self.col < n and not visited[self.row][self.col]:
                res.append(matrix[self.row][self.col])
                visited[self.row][self.col] = 1
                self.col += 1
                move = True
            self.col -= 1
            self.row += 1
            while self.row < m and not visited[self.row][self.col]:
                res.append(matrix[self.row][self.col])
                visited[self.row][self.col] = 1
                self.row += 1
                move = True
            self.row -= 1
            self.col -= 1
            while self.col >= 0  and not visited[self.row][self.col]:
                res.append(matrix[self.row][self.col])
                visited[self.row][self.col] = 1
                self.col -= 1
                move = True
            self.col += 1
            self.row -= 1
            while self.row >= 0 and not visited[self.row][self.col]:
                res.append(matrix[self.row][self.col])
                visited[self.row][self.col] = 1
                self.row -= 1
                move = True
            self.row += 1
            self.col += 1
            if move:
                spiral()
        spiral()
        return res

Date

2018 年 3 月 19 日

posted @ 2018-03-19 16:53  负雪明烛  阅读(36)  评论(0)    收藏  举报