zoukankan      html  css  js  c++  java
  • 算法题---顺时针打印数组

    思路

    1. 一圈圈的打印,开始点为左上角(0,0)

      1. 第一圈:(0,0)

      2. 第二圈:(1,1)

      3. 第N圈:(n,n)

    2. 总共可以打印多少圈,n为行与列的一半,超出就终止

    python实现

    def print_one_circle(array_input, rows, cols, start):
        ret = []
        if len(array_input) == 0:
            return ret
    
        # 列数
        end_x = cols - 1 - start
        # 行数
        end_y = rows - 1 - start
        # 从左往右打印
        for i in range(start, end_x+1):
            ret.append(array_input[start][i])
        # 从上往下打印
        if start < end_y:
            for i in range(start+1, end_y+1):
                ret.append(array_input[i][end_x])
        # 从右往左打印
        if start < end_y and start < end_x:
            for i in range(end_x - 1, start-1, -1):
                ret.append(array_input[end_y][i])
        # 从下往上打印
        if start < end_y - 1 and start < end_x:
            for i in range(end_y - 1, start, -1):
                ret.append(array_input[i][start])
        return ret
    
    
    def print_matrix(array_input):
        ret = []
        if len(array_input) == 0:
            return ret
        rows = len(array_input)
        cols = len(array_input[0])
        start = 0
        while rows > 2*start and cols > 2*start:
            tmp = print_one_circle(array_input, rows, cols, start)
            ret += tmp
            start += 1
        return ret
    
    
    if __name__ == "__main__":
        array_input = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
        print(print_matrix(array_input))
  • 相关阅读:
    实习日记7.28
    实习日记7.27
    实习总结(第三周)
    实习日记7.26
    实习日记7.25
    实习总结(第二周)
    实习总结(第一周)
    实习日记7.22
    实习日记7.21
    5月4下
  • 原文地址:https://www.cnblogs.com/syw-home/p/13890848.html
Copyright © 2011-2022 走看看