In general, any $n\times n$ magic square of range [1, $n^2$] with odd number $n$ can be solved using the following algorithm:
- Start at the middle grid in the bottom row. This is your 1.
- Move downwards and to the right by one grid. If this move results in a position outside the square, wrap around to the beginning of the row (or column).
- If 2 cannot be performed (i.e. the grid is already occupied or you are at the bottom-right corner), move upwards by one grid instead.
- Repeat 2 (or 3) until all numbers are filled.
Illustration using $n=3$. (For cells 2 and 3 the position before wrapping is shown in parentheses.)
| | | |
| | | |
| | 1 | | // start here
| | | 2 |
| | | |
| | 1 | | // move to the right and then down.
(2) // Because moving down brings us outside the square,
// we wrap around to the start of the column
| | | 2 |
| 3 | | | (3)
| | 1 | | // move to the right and down.
// moving right brings us outside, so wrap around to start of row
| 4 | | 2 |
| 3 | | |
| | 1 | | // cannot move down and right because that is occupied
// so we move up instead
| 4 | | 2 |
| 3 | 5 | |
| | 1 | | // move down and right
| 4 | | 2 |
| 3 | 5 | |
| | 1 | 6 | // move down and right
| 4 | | 2 |
| 3 | 5 | 7 |
| | 1 | 6 | // cannot move down and right, so move up
| 4 | | 2 |
| 3 | 5 | 7 |
| 8 | 1 | 6 | // move down and right, wrap around to start of row
| 4 | 9 | 2 |
| 3 | 5 | 7 |
| 8 | 1 | 6 | // move down and right, wrap around to start of column
Now, if you need to solve your magic square that starts with 3, simply add 2 to all cells of this standard square. Then rotate and/or reflect it until you get one where the numbers match your given ones.
For example, consider your first square (assuming we can omit 12):
| | 5 | |
| | | |
| 8 | | |
We first add 2 to all elements of our standard square:
| 6 | 11 | 4 |
| 5 | 7 | 9 |
| 10 | 3 | 8 |
Then rotate clockwise by 90 degrees:
| 10 | 5 | 6 |
| 3 | 7 | 11 |
| 8 | 9 | 4 |
Your first square solved.
Further reading: Magic Square from Wolfram MathWorld, which includes methods for solving even squares as well.