0% found this document useful (0 votes)
2 views3 pages

Magic Square Recursion

This Java program generates a magic square of a given size using recursion. It initializes a matrix, fills it according to the magic square rules, and prints the resulting matrix. The user is prompted to enter the size of the grid, and the program handles edge cases and checks for filled positions during the filling process.

Uploaded by

basakj216
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Magic Square Recursion

This Java program generates a magic square of a given size using recursion. It initializes a matrix, fills it according to the magic square rules, and prints the resulting matrix. The user is prompted to enter the size of the grid, and the program handles edge cases and checks for filled positions during the filling process.

Uploaded by

basakj216
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

import [Link].

Scanner;

public class magicSqRec {

public void MagicSq(int[][] matrix, int col, int row, int num, int size) {

if(num > size * size) { // base case or return case


return;
}
matrix[row][col] = num;

if(row == 0 && col == size - 1) { // edge case


row = 1;
MagicSq(matrix, col, row, num + 1, size);
}

else if(matrix[(row - 1 + size) % size][(col + 1) % size] == 0) { // check filled or not


row = (row - 1 + size) % size;
col = (col + 1) % size;
MagicSq(matrix, col, row, num + 1, size);
}

else {
row = (row + 1 + size) % size;
MagicSq(matrix, col, row, num + 1, size);
}
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

[Link]("Enter the size of grid : ");


int m = [Link]();
int[][] matrix = new int [m][m];

for(int i = 0; i < m; i++) {


for(int j = 0; j < m; j++) {
matrix[i][j] = 0;
}
}

int mid = 0 + (m - 0)/2;

magicSqRec MS = new magicSqRec();

[Link](matrix, mid, 0, 1, [Link]);

[Link]();
for(int i = 0; i < m; i++) {
for(int j = 0; j < m; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
}
}

Output :

You might also like