leetcode 766 托普利茨矩阵

package com.example.lettcode.dailyexercises;

/**
 * @Class IsToeplitzMatrix
 * @Description 766 托普利茨矩阵
 * 给你一个 m x n 的矩阵 matrix 。如果这个矩阵是托普利茨矩阵,返回 true ;否则,返回 false 。
 * 如果矩阵上每一条由左上到右下的对角线上的元素都相同,那么这个矩阵是 托普利茨矩阵 。
 * <p>
 * 示例 1:
 * 输入: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 。
 * <p>
 * 示例 2:
 * 输入:matrix = [[1,2],[2,2]]
 * 输出:false
 * 解释:
 * 对角线 "[1, 2]" 上的元素不同。
 * <p>
 * 提示:
 * m == matrix.length
 * n == matrix[i].length
 * 1 <= m, n <= 20
 * 0 <= matrix[i][j] <= 99
 * @Author
 * @Date 2021/2/22
 **/
public class IsToeplitzMatrix {
    public static boolean isToeplitzMatrix(int[][] matrix) {
        /**
         * 需要分别区分纵横下标的范围
         */
        if (matrix == null || matrix.length == 0) return false;
        if(matrix.length==1 || matrix[0].length==1) return true;
        int startX = matrix.length - 1;
        while (startX >= 0) {
            int indexX = startX;
            int indexY = 0;
            int tmp = matrix[indexX][indexY];
            while (indexY < matrix[0].length && indexX < matrix.length) {
                if (matrix[indexX][indexY] != tmp) return false;
                indexX++;
                indexY++;
            }
            startX--;
        }
        int startY = 1;
        while (startY < matrix[0].length) {
            int indexX = 0;
            int indexY = startY;
            int tmp = matrix[indexX][startY];
            while (indexY < matrix[0].length && indexX < matrix.length) {
                if (matrix[indexX][indexY] != tmp) return false;
                indexX++;
                indexY++;
            }
            startY++;
        }
        return true;
    }
}
// 测试用例
public static void main(String[] args) {
	int[][] matrix = new int[][]{{1, 2, 3, 4}, {5, 1, 2, 3}, {9, 5, 1, 2}};
	boolean ans = IsToeplitzMatrix.isToeplitzMatrix(matrix);
	System.out.println("IsToeplitzMatrix demo01 result:" + ans);

	matrix = new int[][]{{1, 2}, {2, 2}};
	ans = IsToeplitzMatrix.isToeplitzMatrix(matrix);
	System.out.println("IsToeplitzMatrix demo02 result:" + ans);

	matrix = new int[][]{{18}, {66}};
	ans = IsToeplitzMatrix.isToeplitzMatrix(matrix);
	System.out.println("IsToeplitzMatrix demo03 result:" + ans);

	matrix = new int[][]{{11,74,0,93},{40,11,74,7}};
	ans = IsToeplitzMatrix.isToeplitzMatrix(matrix);
	System.out.println("IsToeplitzMatrix demo04 result:" + ans);
}
原文地址:https://www.cnblogs.com/fyusac/p/14430531.html