How to fill matrix in spiral form start from center in C

1 Answer

0 votes
#include <stdio.h>

#define ROWS 5
#define COLS 5

void printMatrix(int matrix[][COLS]) {
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            printf("%4d", matrix[i][j]);
        }
        printf("\n");
    }
}

void fill_matrix_in_spiral_form_start_from_center(int matrix[][COLS], int size) {
    int diry[] = { 1,  0, -1, 0 };
    int dirx[] = { 0, -1,  0, 1 };

    int directions = 4;

    int rings = (size - 1) / 2;
    int x = rings, y = rings;
    int repeats = 0;

    int value = 1;

    matrix[y][x] = value++;

    for (int ring = 0; ring < rings; ring++) {
        y--;
        x++;
        repeats += 2;
        for (int direction = 0; direction < directions; direction++) {
            for (int repeat = 0; repeat < repeats; repeat++) {
                y += diry[direction];
                x += dirx[direction];
                matrix[y][x] = value++;
            }
        }
    }
}

int main() {
    int matrix[ROWS][COLS] = { { 0 } };

    fill_matrix_in_spiral_form_start_from_center(matrix, ROWS);

    printMatrix(matrix);

    return 0;
}




/*
run:

  21  22  23  24  25
  20   7   8   9  10
  19   6   1   2  11
  18   5   4   3  12
  17  16  15  14  13

*/

 



answered Nov 23, 2023 by avibootz
edited May 5, 2024 by avibootz

Related questions

1 answer 217 views
1 answer 216 views
1 answer 185 views
1 answer 192 views
1 answer 197 views
1 answer 219 views
1 answer 216 views
...