zoukankan      html  css  js  c++  java
  • python 生成螺旋矩阵

     螺旋矩阵,像下面这样,看了就能理解,不多解释了。

    [[ 1.  2.  3.  4.  5.  6.]
     [20. 21. 22. 23. 24.  7.]
     [19. 32. 33. 34. 25.  8.]
     [18. 31. 36. 35. 26.  9.]
     [17. 30. 29. 28. 27. 10.]
     [16. 15. 14. 13. 12. 11.]]

    说一下我的思路:
    1.先生成一个零矩阵,再往里面填充数字;
    2.每填充完一个,都判断下一步该往哪走,下一步有四种状态:横+、纵+、横-、纵-,依次循环。
    3.每种状态间切换的条件:原状态的下一步的元素已被填充(!=0)或索引溢出。

    下面是一种具体实现(上面只是整体思路,与实现并不完全对应):
     1 import numpy as np
     2 def r_matrix(n):
     3     mt = np.zeros(n**2).reshape(n,n)
     4     x, y = 0, 0
     5     num = 1
     6     direction = 1
     7     
     8     while mt[x][y] == 0:
     9         mt[x][y] = num
    10         num += 1
    11         if -1<y+direction<n  and mt[x][y+direction] == 0:
    12             y += direction
    13         elif x+direction<n and mt[x+direction][y] == 0:
    14             x += direction
    15         else:
    16             direction = -direction
    17             y += direction
    18     return mt  
  • 相关阅读:
    爬取网页图片
    python 猜数字游戏
    位移运算
    生成随机的名字
    不截半个汉字
    一致性hash的实现
    安装前端脚手架
    什么是快速排序?
    HTML5有趣的标签
    stopPropagation / stopImmediatePropagation
  • 原文地址:https://www.cnblogs.com/pyonwu/p/12215086.html
Copyright © 2011-2022 走看看