ম্যাজিক স্কোয়ার হলো একটি স্কোয়ার ম্যাট্রিক্স, যার অর্ডার বিজোড় এবং যেখানে প্রতিটি রো, কলাম এবং ডায়াগোনালের এলিমেন্টের যোগফল একই থাকে।

প্রতিটি রো, কলাম বা ডায়াগোনালের যোগফল এই ফর্মুলা দিয়ে বের করা যায়: n(n² + 1)/2
ম্যাজিক স্কোয়ার তৈরি করার নিয়মগুলো নিচে দেওয়া হলো −
- ম্যাট্রিক্সের প্রথম রোয়ের মাঝপথি কলাম থেকে শুরু করব এবং সবসময় টপ-লেফট কর্নারের দিকে যাবার চেষ্টা করব পরবর্তী সংখ্যা রাখতে।
- যদি রো এক্সিড করে বা রো ম্যাট্রিক্সে না থাকে, তবে কলাম বাম দিকে চেঞ্জ করুন এবং সংখ্যাটি ম্যাট্রিক্সের লাস্ট রোতে রাখুন, তারপর আবার টপ-লেফট কর্নারের দিকে যান।
- যদি কলাম এক্সিড করে বা কলাম ম্যাট্রিক্সে না থাকে, তবে রো টপ রোতে চেঞ্জ করুন এবং সংখ্যাটি সেই ম্যাট্রিক্সের লাস্ট কলামে রাখুন, তারপর আবার টপ-লেফট কর্নারের দিকে যান।
- যখন টপ-লেফট কর্নার খালি না থাকে বা রো এবং কলাম দুটোই রেঞ্জ ছাড়া যায়, তবে সংখ্যাটি লাস্ট রখা সংখ্যার নিচে রাখুন।
ইনপুট এবং আউটপুট
ইনপুট: ম্যাট্রিক্সের অর্ডার 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
অ্যালগরিদম
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 // টপ রোয়ের সেন্টার
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উদাহরণ (C++)
#include#include 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; } } int 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