首页 > 技术文章 > Leetcode刷题C#版之Toeplitz Matrix

CodeArtist 2018-01-31 14:30 原文

题目:

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(0); //第一维的长度(即行数)
            int col = matrix.GetLength(1); //第二维的长度(即列数)

            for(int i=0;i< row;i++)
            {
                for(int j=0;j< col;j++)
                {
                    //最后一列和最后一行不需要去判断
                    if(j+1!= col&& i+1!= row)
                    {
                        //如果下一行下一列有不相等的就说明不满足条件
                        if(matrix[i,j]!= matrix[i+1, j+1])
                        {
                            flag = false;
                            break;
                        }
                    }
                }
                if(!flag)
                {
                    break;
                }
            }
            return flag;
        }

 

推荐阅读