Looping in a spiral

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

    Java spiral "Code golf" attempt, based on the C++ variant.

    public static void Spiral(int X, int Y) {
        int x=0, y=0, dx = 0, dy = -1;
        int t = Math.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)) {
                System.out.println(x+","+y);
                //DO STUFF
            }
    
            if( (x == y) || ((x < 0) && (x == -y)) || ((x > 0) && (x == 1-y))) {
                t=dx; dx=-dy; dy=t;
            }   
            x+=dx; y+=dy;
        }
    }
    

提交回复
热议问题