zoukankan      html  css  js  c++  java
  • 19.顺时针打印矩阵(python)

    题目描述

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

     1 # -*- coding:utf-8 -*-
     2 class Solution:
     3     # matrix类型为二维列表,需要返回列表
     4     def printMatrix(self, matrix):
     5         # write code here
     6         def help(topRow,topCol,botRow,botCol):
     7             
     8             if topRow == botRow:#只有一行:
     9                 while topCol <=botCol:
    10                     res.append(matrix[topRow][topCol])
    11                     topCol+=1
    12             elif topCol == botCol:#只有一行
    13                 while topRow<=botRow:
    14                     res.append(matrix[topRow][topCol])
    15                     topRow+=1
    16             else:
    17                 curCol=topCol
    18                 curRow=topRow
    19                 while curCol<botCol:
    20                     res.append(matrix[topRow][curCol])
    21                     curCol+=1
    22                 while curRow<botRow:
    23                     res.append(matrix[curRow][botCol])
    24                     curRow+=1
    25                 while curCol>topCol:
    26                     res.append(matrix[botRow][curCol])
    27                     curCol-=1
    28                 while curRow>topRow:
    29                     res.append(matrix[curRow][topCol])
    30                     curRow-=1
    31         if len(matrix)==1:
    32             return matrix[0]
    33         res=[]
    34         topRow=0
    35         topCol=0
    36         botRow=len(matrix)-1
    37         botCol=len(matrix[0])-1
    38         
    39         while topRow<=botRow and topCol<=botCol:
    40             help(topRow,topCol,botRow,botCol)
    41             topRow+=1
    42             topCol+=1
    43             botRow-=1
    44             botCol-=1
    45         return res
  • 相关阅读:
    CSS边框(圆角、阴影、背景图片)
    CSS3浏览器兼容
    HTML5全局属性
    HTLM5新增属性
    HTML5标签
    如何开始使用bootstrap
    重新了解Java基础(三)-运行机制&HelloWorld
    重新了解Java基础(二)-Java的特性
    Java关键字之native
    重新了解Java基础(一)
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/12013127.html
Copyright © 2011-2022 走看看