Looping in a spiral

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

    C++ anyone? Quick translation from python, posted for completeness

    void Spiral( int X, int Y){
        int x,y,dx,dy;
        x = y = dx =0;
        dy = -1;
        int t = std::max(X,Y);
        int maxI = t*t;
        for(int i =0; i < maxI; i++){
            if ((-X/2 <= x) && (x <= X/2) && (-Y/2 <= y) && (y <= Y/2)){
                // DO STUFF...
            }
            if( (x == y) || ((x < 0) && (x == -y)) || ((x > 0) && (x == 1-y))){
                t = dx;
                dx = -dy;
                dy = t;
            }
            x += dx;
            y += dy;
        }
    }
    

提交回复
热议问题