ম্যাজিক বর্গ হল একটি বর্গাকার ম্যাট্রিক্স, যার ক্রম বিজোড় এবং যেখানে প্রতিটি সারি বা প্রতিটি কলাম বা প্রতিটি তির্যকের উপাদানগুলির যোগফল একই৷

এই সূত্র ব্যবহার করে প্রতিটি সারি বা প্রতিটি কলাম বা প্রতিটি তির্যকের যোগফল পাওয়া যাবে। 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