I am working on a magic square problem, the size of the square will be an odd number between 3 to 99. Here is the result of a 5x5 square:
15 8 1 24 17
16 14 7 5 23
22 20 13 6 4
3 21 19 12 10
9 2 25 18 11
The program works fine with a for loop, but I've been asked to rewrite this using recursion.
Can anyone give me some direction? Much appreciated!
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
square[i][j] = 0;
}
}
square[i][j] = k; // Start from the middle of the first row (1)
for (k = 2; k <= size * size; k++) {
// Move up and left
if (square[I][j]) {
// Move down if space is occupied
}
square[I][j] = k;
}
I tried to rewrite it in recursive, but got "Segmentation fault: 11".
void magic(int square[][size], int size, int k, int i, int j) {
if (k >= size * size) {
return;
} else {
// Move up and left
if (square[I][j]) {
// Move down if space is occupied
}
square[I][j] = k;
magic(square, size, k + 1, i, j);
}
}