Looping in a spiral

前端 未结 30 2810
独厮守ぢ
独厮守ぢ 2020-11-22 15:07

A friend was in need of an algorithm that would let him loop through the elements of an NxM matrix (N and M are odd). I came up with a solution, but I wanted to see if my fe

30条回答
  •  猫巷女王i
    2020-11-22 15:30

    I love python's generators.

    def spiral(N, M):
        x,y = 0,0   
        dx, dy = 0, -1
    
        for dumb in xrange(N*M):
            if abs(x) == abs(y) and [dx,dy] != [1,0] or x>0 and y == 1-x:  
                dx, dy = -dy, dx            # corner, change direction
    
            if abs(x)>N/2 or abs(y)>M/2:    # non-square
                dx, dy = -dy, dx            # change direction
                x, y = -y+dx, x+dy          # jump
    
            yield x, y
            x, y = x+dx, y+dy
    

    Testing with:

    print 'Spiral 3x3:'
    for a,b in spiral(3,3):
        print (a,b),
    
    print '\n\nSpiral 5x3:'
    for a,b in spiral(5,3):
        print (a,b),
    

    You get:

    Spiral 3x3:
    (0, 0) (1, 0) (1, 1) (0, 1) (-1, 1) (-1, 0) (-1, -1) (0, -1) (1, -1) 
    
    Spiral 5x3:
    (0, 0) (1, 0) (1, 1) (0, 1) (-1, 1) (-1, 0) (-1, -1) (0, -1) (1, -1) (2, -1) (2, 0) (2, 1) (-2, 1) (-2, 0) (-2, -1)
    

提交回复
热议问题