Dsa
Backtracking
Medium
Magic Square Generator
You are tasked with creating a magic square of size n x n, where n is an odd integer (1 ≤ n ≤ 15). A magic square is a square matrix where the sums of the numbers in each row, each column, and both main diagonals are all the same. Write a program that outputs one valid magic square configuration using numbers from 1 to n^2.
Input format:
- A single integer n (odd, 1 ≤ n ≤ 15).
Output format:
- The program should print the magic square as n lines of space-separated integers.
Example:
Input:
3
Output:
8 1 6
3 5 7
4 9 2
The output may vary, but it should always be a valid magic square.
Key concepts
backtrackingmatrixcombinatorial generation
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now