Looping in a spiral

前端 未结 30 2740
独厮守ぢ
独厮守ぢ 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:19

    This is based on your own solution, but we can be smarter about finding the corners. This makes it easier to see how you might skip over the areas outside if M and N are very different.

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

    and a generator based solution that is better than O(max(n,m)^2), It is O(nm+abs(n-m)^2) because it skips whole strips if they are not part of the solution.

    def spiral(X,Y):
    X = X+1>>1
    Y = Y+1>>1
    x = y = 0
    d = side = 1
    while x

提交回复
热议问题