Leetcode刷题C#版之Toeplitz Matrix

题目:

Toeplitz Matrix

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

Now given an M x N matrix, return True if and only if the matrix is Toeplitz.

Example 1:

Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: True
Explanation:
1234
5123
9512

In the above grid, the diagonals are "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]", and in each diagonal all elements are the same, so the answer is True.

Example 2:

Input: matrix = [[1,2],[2,2]]
Output: False
Explanation:
The diagonal "[1, 2]" has different elements.

Note:

matrix will be a 2D array of integers.
matrix will have a number of rows and columns in range [1, 20].
matrix[i][j] will be integers in range [0, 99].

拿到题目最容易的就是想到遍历数组的行和列,判断某行某列与该行+1和该列+1的值是否相等。C#版本的代码如下(关键步骤已经注释)

public static bool IsToeplitzMatrix(int[,] matrix)
{
bool flag = true; int row = matrix.GetLength(); //第一维的长度(即行数)
int col = matrix.GetLength(); //第二维的长度(即列数) for(int i=;i< row;i++)
{
for(int j=;j< col;j++)
{
//最后一列和最后一行不需要去判断
if(j+!= col&& i+!= row)
{
//如果下一行下一列有不相等的就说明不满足条件
if(matrix[i,j]!= matrix[i+, j+])
{
flag = false;
break;
}
}
}
if(!flag)
{
break;
}
}
return flag;
}
上一篇:[Locked] Binary Tree Upside Down


下一篇:原生Js弹窗插件|web弹出层组件|对话框