美文网首页
顺时针打印矩阵

顺时针打印矩阵

作者: 九日火 | 来源:发表于2021-01-03 13:49 被阅读0次

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

    例如, 如果输入如下矩阵:

    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

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    class Solution:
        def PrintMatirx(self, matrix):
            if matrix == None:
                return
    
            if matrix == []:
                return
            Array = []
            start = 0
            columns = len(matrix)
            rows = len(matrix[0])
    
            while columns > start * 2 and rows > start * 2:
                endX = columns - 1 - start
                endY = rows -1 - start
    
                for i in range(start, endX+1):
                    num = matrix[start][i]
                    Array.append(num)
    
                if start < endY:
                    for i in range(start+1, endY+1):
                        num = matrix[i][endX]
                        Array.append(num)
    
                if start < endX and start < endY:
                    for i in range(endX-1, start-1, -1):
                        num = matrix[endY][i]
                        Array.append(num)
    
                if start < endX and start < endY - 1:
                    for i in range(endY-1, start-1, -1):
                        num = matrix[i][endX]
                        Array.append(num)
    
                start += 1
            return  Array
    
    
    package main
    
    
    func PrintMatrix(matrix [][]int) []int {
        var res []int
        n := len(matrix)
        if n==0 {return res}
    
        m := len(matrix[0])
    
        nm := n*m
        layer := 0 
    
        startN, endN, startM, endM := 0, 0, 0, 0
    
        for nb > 0 {
            startN, endN = layer, n-layer-1
            startM, endM = layer, m-layer-1
    
            for i := startM; i <= endM && nb > 0; i++ {
                res = append(res, matrix[startN][i])
                nb--
            }
    
            for i := startN+1; i<=endM && nb>0; i++ {
                res = append(res, matrix[i][startM])
                nb--
            }
    
            for i := endM-1; i>=startM && nb>0; i++ {
                res = append(res, matrix[endN][i])
                nb--
            }
    
            for i := endN-1; i>=endN && nb>0; i++ {
                res = append(res, matrix[i][startM])
                nb--
            }
            layer++
        }
        return res
    }
    

    相关文章

      网友评论

          本文标题:顺时针打印矩阵

          本文链接:https://www.haomeiwen.com/subject/nqpeoktx.html