Looping in a spiral

前端 未结 30 2693
独厮守ぢ
独厮守ぢ 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条回答
  •  一个人的身影
    2020-11-22 15:30

    Python looping clockwise spiral code using Can Berk Güder answer.

    def spiral(X, Y):
        x = y = 0
        dx = 0
        dy = 1
        for i in range(max(X, Y)**2):
            if (-X/2 < x <= X/2) and (-Y/2 < y <= Y/2):
                print (x, y)
                # DO STUFF...
            if x == -y or (x < 0 and x == y) or (x > 0 and x-1 == y):
                dx, dy = dy, -dx
            x, y = x+dx, y+dy
    

提交回复
热议问题