如何使用 C# 檢查給定的矩陣是否為託普利茨矩陣?


如果矩陣中所有從左上到右下的對角線元素均相同,則該矩陣為託普利茨矩陣。

示例 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]".

每條對角線上的元素均相同,因此答案為 True。

示例 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

更新日期: 2021-08-17

565 次瀏覽

開啟您的 職業

完成課程,透過認證

開始學習
廣告
© . All rights reserved.