如何使用 C# 检查给定矩阵是否为托普利茨矩阵?
csharpserver side programmingprogramming更新于 2025/4/18 11:22:17
如果从左上角到右下角的每个对角线都有相同的元素,则矩阵为托普利茨矩阵。
示例 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
输入:矩阵 [[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

