Magic Square (เมจิกสแควร์) คือเมทริกซ์สี่เหลี่ยมจัตุรัสที่ลำดับ (Order) เป็นเลขคี่ และผลรวมของสมาชิกในแต่ละแถว แต่ละคอลัมน์ และแต่ละเส้นทแยงมุม มีค่าเท่ากัน

ผลรวมแต่ละแถว/คอลัมน์/เส้นทแยงมุม หาได้จากสูตร: n(n² + 1)/2
กติกาการสร้าง Magic Square
- เริ่มจากคอลัมน์กลางของแถวแรก วางตัวเลข 1 แล้วไปมุมซ้ายบนเพื่อวางตัวเลขถัดไป
- ถ้าแถวเกินขอบเขต (ออกนอกเมทริกซ์) ให้เปลี่ยนคอลัมน์เป็นคอลัมน์ซ้ายสุด และวางตัวเลขที่แถวสุดท้าย แล้วไปมุมซ้ายบนอีกครั้ง
- ถ้าคอลัมน์เกินขอบเขต ให้เปลี่ยนแถวเป็นแถวบนสุด และวางตัวเลขที่คอลัมน์สุดท้าย แล้วไปมุมซ้ายบนอีกครั้ง
- ถ้ามุมซ้ายบนไม่ว่าง หรือทั้งแถวและคอลัมน์เกินขอบเขต ให้วางตัวเลขด้านล่างของตัวเลขที่วางล่าสุด
Input และ Output
Input: ลำดับเมทริกซ์ 5 Output: 15 8 1 24 17 16 14 7 5 23 22 20 13 6 4 3 21 19 12 10 9 2 25 18 11
Algorithm
createSquare(mat, r, c)
Input: เมทริกซ์
Output: แถวและคอลัมน์
Begin
count := 1
fill all elements in mat to 0
range := r * c
i := 0, j := c/2
mat[i, j] := count // กลางแถวบนสุด
while count < range do
increase count by 1
if both i and j crosses matrix range then
increase i by 1
else if only i crosses range then
i := c - 1; decrease j by 1
else if only j crosses range then
j := c - 1; decrease i by 1
else if i,j in matrix and mat[i,j] ≠ 0 then
increase i by 1
else
decrease i and j by 1
mat[i, j] := count
done
display matrix mat
End
ตัวอย่างโค้ด (C++)
#include <iostream>
#include <iomanip>
using namespace std;
void createSquare(int **array, int r, int c) {
int i, j, count = 1, range;
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
array[i][j] = 0;
range = r*c;
i = 0; j = c/2;
array[i][j] = count;
while(count < range) {
count++;
if((i-1) < 0 && (j-1) < 0)
i++;
else if((i-1) < 0) {
i = r-1; j--;
} else if((j-1) < 0) {
j = c-1; i--;
} else if(array[i-1][j-1] != 0)
i++;
else {
i--; j--;
}
array[i][j] = count;
}
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++)
cout << setw(3) << array[i][j];
cout << endl;
}
}
main() {
int** matrix;
int row, col;
cout << "Enter the order(odd) of square matrix :";
cin >> row;
col = row;
matrix = new int*[row];
for(int i = 0; i < row; i++)
matrix[i] = new int[col];
createSquare(matrix, row, col);
}
Output
Enter the order(odd) of square matrix :5 15 8 1 24 17 16 14 7 5 23 22 20 13 6 4 3 21 19 12 10 9 2 25 18 11