Algorithm for iterating over an outward spiral on a discrete 2D grid from the origin

前端 未结 12 1701
独厮守ぢ
独厮守ぢ 2020-12-05 06:54

For example, here is the shape of intended spiral (and each step of the iteration)

          y
          |
          |
   16 15 14 13 12
   17  4  3  2 11
--         


        
12条回答
  •  半阙折子戏
    2020-12-05 07:32

    There's nothing wrong with direct, "ad-hoc" solution. It can be clean enough too.
    Just notice that spiral is built from segments. And you can get next segment from current one rotating it by 90 degrees. And each two rotations, length of segment grows by 1.

    edit Illustration, those segments numbered

       ... 11 10
    7 7 7 7 6 10
    8 3 3 2 6 10
    8 4 . 1 6 10
    8 4 5 5 5 10
    8 9 9 9 9  9
    

    .

        // (di, dj) is a vector - direction in which we move right now
        int di = 1;
        int dj = 0;
        // length of current segment
        int segment_length = 1;
    
        // current position (i, j) and how much of current segment we passed
        int i = 0;
        int j = 0;
        int segment_passed = 0;
        for (int k = 0; k < NUMBER_OF_POINTS; ++k) {
            // make a step, add 'direction' vector (di, dj) to current position (i, j)
            i += di;
            j += dj;
            ++segment_passed;
            System.out.println(i + " " + j);
    
            if (segment_passed == segment_length) {
                // done with current segment
                segment_passed = 0;
    
                // 'rotate' directions
                int buffer = di;
                di = -dj;
                dj = buffer;
    
                // increase segment length if necessary
                if (dj == 0) {
                    ++segment_length;
                }
            }
        }
    

    To change original direction, look at original values of di and dj. To switch rotation to clockwise, see how those values are modified.

提交回复
热议问题