Looping in a spiral

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

    Here is my attempt for simple C solution. First print the outer spiral and move one block inside..and repeat.
    
    #define ROWS        5
    #define COLS        5
    //int A[ROWS][COLS] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {11, 12, 13, 14}, {15, 16, 17, 18} };
    //int A[ROWS][COLS] = { {1, 2, 3}, {6, 7, 8}, { 12, 13, 14} };
    //int A[ROWS][COLS] = { {1, 2}, {3, 4}};
    
    int A[ROWS][COLS] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15} , {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25} };
    
    
    void print_spiral(int rows, int cols)
    {
        int row = 0;
        int offset = 0;
    
        while (offset < (ROWS - 1)) {
            /* print one outer loop at a time. */
            for (int col = offset; col <= cols; col++) {
                printf("%d ", A[offset][col]);
            }
    
            for (row = offset + 1; row <= rows; row++) {
                printf("%d ", A[row][cols]);
            }
    
            for (int col = cols - 1; col >= offset; col--) {
                printf("%d ", A[rows][col]);
            }
    
            for (row = rows - 1; row >= offset + 1; row--) {
                printf("%d ", A[row][offset]);
            }
    
           /* Move one block inside */
            offset++;
            rows--;
            cols--;
        }
        printf("\n");
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        print_spiral(ROWS-1, COLS-1);
        return 0;
    }
    

提交回复
热议问题