The question involves generating a magic square where recursion is used to fill
ID: 3657042 • Letter: T
Question
The question involves generating a magic square where recursion is used to fill in the array values. I have the iterative solution working correctly - I just need to change the loop into recursion. Any help would be greatly appreciated. int[][] square = new int[n][n]; square[0][(n-1)/2] = 1; int key = 2; int i = 0; int j = (n-1)/2; while(key <= Math.pow(n,2)) { int k = i-1; if(k < 0) { k += n; } int l = j-1; if(l < 0) l += n; if(square[k][l] != 0) i = (i + 1) % n; else { i=k; j=l; } square[i][j]=key; key++; } for(i=0; i < n; i++) { for(j=0; j < n; j++) System.out.print(square[i][j] + " "); System.out.println(); } }Explanation / Answer
#include /* Recursive function, square, for allocating values within the magic square */ int square(int row, int col, int m, int nextvalue, int *S[][m]){ int nextval = nextvalue; int n = m; if (nextvalue == 1){ //for first number placement S[row][col] = 1; square(row - 1, col + 1, m, nextvalue + 1, S[m][m]); //return (square(row - 1, col + 1, m, nextvalue + 1, S[m][m])); } if (nextval = m){ //when nextvalue = n, end recursive function call return 1; } if (row < 0){ //to check and see if the next row'th location is within range of n row = m - 1; } if (col > (m - 1)){ //to check and see if the next col'th location is within range of n col = 0; } else { //check to see if the next spot is available if (S[row][col] = 0){ S[row][col] = nextval; square(row - 1, col + 1, m, nextvalue + 1, S[m][m]); //return (square(row - 1, col + 1, m, nextval + 1, S[m][m])); } else if (S[row][col] != 0){ if (col == 0){ col = m - 1; } else if (col > 0){ col = col - 1; } if (row >= (m-2) || row == (m-1)){ row = (row + 2) - m; } else if (rowRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.