C#LeetCode刷题之#766-托普利茨矩阵(Toeplitz Matrix)

版权声明:Iori 的技术分享,所有内容均为本人原创,引用请注明出处,谢谢合作! https://blog.csdn.net/qq_31116753/article/details/82470405

问题

如果一个矩阵的每一方向由左上到右下的对角线上具有相同元素,那么这个矩阵是托普利茨矩阵。

给定一个 m * n 的矩阵,当且仅当它是托普利茨矩阵时返回 True。

输入: 
matrix = [
  [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。

输入:
matrix = [
  [1,2],
  [2,2]
]

输出: False

解释: 对角线"[1, 2]"上的元素不同。

说明:

matrix 是一个包含整数的二维数组。
matrix 的行数和列数均在 [1, 20]范围内。
matrix[i][j] 包含的整数在 [0, 99]范围内。

进阶:

如果矩阵存储在磁盘上,并且磁盘内存是有限的,因此一次最多只能将一行矩阵加载到内存中,该怎么办?
如果矩阵太大以至于只能一次将部分行加载到内存中,该怎么办?


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

Now given an m * n matrix, return True if and only if the matrix is Toeplitz.

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.

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].


示例

public class Program {

    public static void Main(string[] args) {
        int[,] cost = null;

        cost = new int[,] {{ 1, 2, 3, 4 },
                           { 5, 1, 2, 3},
                           { 9, 5, 1, 2}
        };
        var res = IsToeplitzMatrix(cost);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static bool IsToeplitzMatrix(int[,] matrix) {
        //暴力解法
        for(int i = 0; i < matrix.GetLength(0) - 1; i++) {
            for(int j = 0; j < matrix.GetLength(1) - 1; j++) {
                if(matrix[i + 1, j + 1] != matrix[i, j]) {
                    return false;
                }
            }
        }
        return true;
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

True

分析:

显而易见,以上算法的时间复杂度为: O(m*n) 。

猜你喜欢

转载自blog.csdn.net/qq_31116753/article/details/82470405
今日推荐