mskf
V2EX  ›  算法

找到一个二重循环遍历某个点的上下左右四个临近点的方法

  •  
  •   mskf · Oct 18, 2019 · 4298 views
    This topic created in 2409 days ago, the information mentioned may be changed or developed.

    在同一个循环中,也可以遍历四个斜着的临近点

    for i in [-1,1]:
        for j in [-1,1]:
        	# top,left,right,bottom
        	nx, ny = x+(i+j)//2,y+(i-j)//2
            
            # corners
            nx, ny = x+i,y+j
    

    以前都是写死 x+1,y x,y+1... 然后遍历,或者用三角函数循环角度,感觉上面写更简洁

    3 replies    2019-10-18 00:12:11 +08:00
    ZRS
        1
    ZRS  
       Oct 18, 2019
    巧妙
    taotaodaddy
        2
    taotaodaddy  
       Oct 18, 2019 via Android
    棒棒
    mskf
        3
    mskf  
    OP
       Oct 18, 2019
    如果在其他语言中使用 for I = 0 to 1 遍历,只需要在开头加上 i=1-2*I, j=1-2*J 就可以了,下面完全一样
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   934 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 20:02 · PVG 04:02 · LAX 13:02 · JFK 16:02
    ♥ Do have faith in what you're doing.