เมจิกสแควร์เป็นเมทริกซ์สี่เหลี่ยมจัตุรัสซึ่งมีลำดับเป็นเลขคี่และโดยที่ผลรวมขององค์ประกอบสำหรับแต่ละแถวหรือแต่ละคอลัมน์หรือแต่ละแนวทแยงเท่ากัน

ผลรวมของแต่ละแถวหรือแต่ละคอลัมน์หรือแต่ละแนวทแยงสามารถพบได้โดยใช้สูตรนี้ n(n2+ 1)/2
นี่คือกฎสำหรับการสร้างจตุรัสเวทมนตร์ -
- เราจะเริ่มจากคอลัมน์กลางของแถวแรก ของเมทริกซ์ และไปที่มุมซ้ายบนเสมอเพื่อวางหมายเลขถัดไป
- หากแถวเกินหรือแถวนั้นไม่อยู่ในเมทริกซ์ ให้เปลี่ยนคอลัมน์เป็นคอลัมน์ด้านซ้ายแล้ววางตัวเลขที่แถวสุดท้ายของเมทริกซ์ แล้วไปที่มุมซ้ายบนอีกครั้ง
- หากคอลัมน์เกินหรือคอลัมน์ไม่อยู่ในเมทริกซ์ ให้เปลี่ยนแถวเป็นแถวบนสุดแล้ววางตัวเลขที่คอลัมน์สุดท้ายของเมทริกซ์นั้น จากนั้นไปที่มุมซ้ายบนอีกครั้ง
- เมื่อมุมซ้ายบนไม่ว่างหรือทั้งแถวและคอลัมน์เกินช่วง ให้วางตัวเลขที่ด้านล่างของตัวเลขที่วางสุดท้าย
อินพุตและเอาต์พุต
Input: The order of the matrix 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
อัลกอริทึม
createSquare(mat, r, c)
ป้อนข้อมูล: เมทริกซ์
ผลลัพธ์: แถวและคอลัมน์
Begin count := 1 fill all elements in mat to 0 range := r * c i := 0 j := c/2 mat[i, j] := count //center of top row while count < range, do increase count by 1 if both i and j crosses the matrix range, then increase i by 1 else if only i crosses the matrix range, then i := c – 1 decrease j by 1 else if only j crosses the matrix range, then j := c – 1 decrease i by 1 else if i and j are in the matrix and element in (i, j) ≠ 0, then increase i by 1 else decrease i and j by 1 mat[i, j] := count done display the matrix mat End
ตัวอย่าง
#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; //initialize all elements with 0
range = r*c;
i = 0;
j = c/2;
array[i][j] = count;
while(count < range) {
count++;
if((i-1) < 0 && (j-1) < 0) //when both row and column crosses the range
i++;
else if((i-1) <0) { //when only row crosses range, set i to last row, and decrease j
i = r-1;
j--;
}else if((j-1) < 0) { //when only col crosses range, set j to last column, and decrease i
j = c-1;
i--;
}else if(array[i-1][j-1] != 0) //when diagonal element is not empty, go to next row
i++;
else{
i--;
j--;
}
array[i][j] = count;
}
// Printing the square
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);
} ผลลัพธ์
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