Looping in a spiral

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

    This is in C.

    I happened to choose bad variable names. In the names T == top, L == left, B == bottom, R == right. So, tli is top left i and brj is bottom right j.

    #include
    
    typedef enum {
       TLTOR = 0,
       RTTOB,
       BRTOL,
       LBTOT
    } Direction;
    
    int main() {
       int arr[][3] = {{1,2,3},{4,5,6}, {7,8,9}, {10,11,12}};
       int tli = 0, tlj = 0, bri = 3, brj = 2;
       int i;
       Direction d = TLTOR;
    
       while (tli < bri || tlj < brj) {
         switch (d) {
         case TLTOR:
        for (i = tlj; i <= brj; i++) {
           printf("%d ", arr[tli][i]);
        }
        tli ++;
        d = RTTOB;
        break;
         case RTTOB:
        for (i = tli; i <= bri; i++) {
           printf("%d ", arr[i][brj]);
        }
        brj --;
        d = BRTOL;
        break;
         case BRTOL:
        for (i = brj; i >= tlj; i--) {
           printf("%d ", arr[bri][i]);
        }
        bri --;
            d = LBTOT;
        break;
         case LBTOT:
        for (i = bri; i >= tli; i--) {
           printf("%d ", arr[i][tlj]);
        }
        tlj ++;
            d = TLTOR;
        break;
     }
       }
       if (tli == bri == tlj == brj) {
          printf("%d\n", arr[tli][tlj]);
       }
    }
    

提交回复
热议问题