Search code examples
algorithmmagic-square

How to create a magic square which already has some numbers filled?


I would like to do this: I've got a matrix N x N. It can contain number from 1 to n^2. This matrix has a few cells filled with positive numbers. I have to decide, that this already filled matrix can be a magic matrix (magic square). For example:

0 0 0 7 4

0 1 0 0 8

0 0 3 0 0

0 0 0 0 0

0 0 0 0 0 

We can create from this matrix a magic square. Is there any algorithm to decide this? Could you recommend me something? Thank You!


Solution

  • I'm not sure if it is the most efficient approach, but you can determine the magic constant: as

    magic_constant = n*(n^2+1)/2
    

    Once you have the magic constant, you can work it similar to a Sudoku puzzle, where you determine which possible values could work for each unfilled cell, and then try each one starting with the cell that has the fewest possible values. When you fill a cell with a number, you update the possible values for the rest of the unfilled cells. If you run into a case where a cell has no possible values, then you backtrack. If you run out of possibilities, then the answer is "no". If you run out of unfilled cells, then the answer is "yes".