如何使用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP