How to check whether the given matrix is a Toeplitz matrix using C#?


A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.

Example 1

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

Output

true

In the above grid, the diagonals are −

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

In each diagonal all elements are the same, so the answer is True.

Example 2

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

Output

false

The diagonal "[1, 2]" has different elements

Code

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));
   }

Output

TRUE

Updated on: 17-Aug-2021

437 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements