โจทย์
ได้รับเมทริกซ์ 2D สี่เหลี่ยมจัตุรัส mat[][] ขนาด n x n ทางเราต้อง ตรวจสอบว่าเป็นเมทริกซ์ Toeplitz (Diagonal Matrix) หรือไม่
Toeplitz Matrix: ทุกเส้นทแยงมุมจากซ้ายบนไปขวาล่างมีค่าเท่ากัน
ตัวอย่าง
Input: Mat = {{3,5,1}, {4,3,2}, {1,2,3}}
Output: Yes (เส้นทแยงหลักคือ 3,3,3)
แนวทางแก้ปัญหา
ตรวจสอบทุกเส้นทแยงมุม: สำหรับทุก i,j ที่ i>0 และ j>0 ต้องมี mat[i][j] == mat[i-1][j-1]
โปรแกรมตัวอย่าง
#include <iostream>
using namespace std;
#define N 4
bool isToeplizMatrix(int mat[N][N]) {
for (int i = 1; i < N; i++)
for (int j = 1; j < N; j++)
if (mat[i][j] != mat[i-1][j-1]) return false;
return true;
}
int main() {
int mat[N][N] = {{6,7,8,9}, {4,6,7,8}, {1,4,6,7}, {0,1,4,6}};
if (isToeplizMatrix(mat)) cout << "Matrix is a Toepliz matrix.";
else cout << "Matrix is not a Toepliz matrix.";
return 0;
}
ผลลัพธ์
Matrix is a Toepliz matrix.