Looping in a spiral

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

    I am sharing this code which I designed for a different purpose; it is about finding the Column number "X", and the row number "Y" of array element @ spiral index "index". This function takes the width "w" and height "h" of the matrix, and the required "index". Of course, this function can be used to produce the same required output. I think it is the fastest possible method (as it jumps over cells instead of scanning them).

        rec BuildSpiralIndex(long w, long h, long index = -1)
        {  
            long count = 0 , x = -1,  y = -1, dir = 1, phase=0, pos = 0,                            length = 0, totallength = 0;
            bool isVertical = false;
            if(index>=(w*h)) return null;
    
            do 
            {                
                isVertical = (count % 2) != 0;
                length = (isVertical ? h : w) - count/2 - count%2 ;
                totallength += length;
                count++;
            } while(totallength 1 ? phase : w - phase);
            y = ((pos == 1 || pos == 2) ? h - phase : phase) + (1 * (pos == 3 ? 1 : 0));
            dir = pos > 1 ? -1 : 1;
            if (isVertical) y -= (totallength - index - 1) * dir;
            else x -= (totallength - index -1) * dir;
            return new rec { X = x, Y = y };
        }
    

提交回复
热议问题