ที่นี่เราจะดูโปรแกรมหนึ่งที่ช่วยตรวจสอบว่าเมทริกซ์เป็น bisymmetric หรือไม่ Bisymmetric matrix คือเมทริกซ์สี่เหลี่ยมจัตุรัสที่สมมาตรเกี่ยวกับทั้งสองเส้นทแยงมุมหลัก เมทริกซ์ด้านล่างเป็นตัวอย่างของ bisymmetric matrix
1 2 3 4 5 2 6 7 8 4 3 7 9 7 3 4 8 7 6 2 5 4 3 2 1
อัลกอริทึม
checkBiSymmetric(mat, n)
Begin
for i in range 0 to n - 1, do
for j in range 0 to i - 1, do
if mat[i, j] is not same as mat[j, i], then
return false
end if
done
done
for i in range 0 to n - 1, do
for j in range 0 to n - i, do
if mat[i, j] is not same as mat[n - j - 1, n - i - 1], then
return false
end if
done
done
return true
End
ตัวอย่าง
#include<iostream>
#define N 5
using namespace std;
int matrix[N][N] = {{1, 2, 3, 4, 5},
{2, 6, 7, 8, 4},
{3, 7, 9, 7, 3},
{4, 8, 7, 6, 2},
{5, 4, 3, 2, 1}};
bool checkBiSymmetric() {
for (int i = 0; i < N; i++) // scan through forward diagonal
for (int j = 0; j < i; j++)
if (matrix[i][j] != matrix[j][i]) // when corresponding elements are not same, return false
return false;
for (int i = 0; i < N; i++) // scan through forward diagonal
for (int j = 0; j < N - i; j++)
if (matrix[i][j] != matrix[N - j - 1][N - i - 1]) // when corresponding elements are not same, return false
return false;
return true; // otherwise return true
}
int main() {
if(checkBiSymmetric()) {
cout << "Yes the matrix is bisymmetric";
} else {
cout << "No the matrix is not bisymmetric";
}
}
ผลลัพธ์
Yes the matrix is bisymmetric