如何使用 C# 检查给定的矩阵是否是 Toeplitz 矩阵?

如果从左上角到右下角的每条对角线都具有相同的元素,则矩阵是 Toeplitz。

示例 1

[[1,2,3,4],
[5,1,2,3],
[9,5,1,2]]

输出-

true

在上面的网格中,对角线是 -

"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".

在每条对角线上,所有元素都相同,所以答案为真。

示例 2

Input: matrix
[[1,2],
[2,2]]

输出-

false

对角线“[1, 2]”有不同的元素

代码

public class Matrix
   {
   public bool ToeplitzMatrix(int[,] mat)
   {
      int row = getMatrixRowSize(mat);
      int col = getMatrixColSize(mat);
      for (int i = 1; i < row; i++)
      {
         for (int j = 1; j < col; j++)
         {
            if (mat[i, j] != mat[i - 1, j - 1])
            {
               return false;
            }
         }
      }
      return true;
   }
   private int getMatrixRowSize(int[,] mat)
   {
      return mat.GetLength(0);
   }
   private int getMatrixColSize(int[,] mat)
   {
      return mat.GetLength(1);
   }
}
static void Main(string[] args)
   {
      Matrix m = new Matrix();
      int[,] mat = new int[3, 4] { { 1, 2, 3, 4 }, { 5, 1, 2, 3 }, { 9, 5, 1, 2 } };
      Console.WriteLine(m.ToeplitzMatrix(mat));
   }
输出结果
TRUE