Dsa
Backtracking
Medium
Magic Square Formation
You need to create a magic square of size n x n, where the sum of every row, column, and diagonal is the same. Starting from a set of numbers from 1 to n^2, your task is to generate all possible configurations that can form a magic square. Print each unique configuration of the magic square.
Input Format:
- The first line contains an integer n (1 ≤ n ≤ 5), the order of the magic square.
Output Format:
- Print each unique magic square configuration line by line. If no magic square can be formed, print 'No magic square configuration exists.'
Example:
Input:
3
Output:
[8, 1, 6]
[3, 5, 7]
[4, 9, 2]
[4, 9, 2]
[3, 5, 7]
[8, 1, 6]
Key concepts
backtrackingcombinatoricsmatrices
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