【LEETCODE】45、766. Toeplitz Matrix

package y2019.Algorithm.array;

/**
 * @ProjectName: cutter-point
 * @Package: y2019.Algorithm.array
 * @ClassName: IsToeplitzMatrix
 * @Author: xiaof
 * @Description: 766. 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.
 *
 * Input:
 * matrix = [
 *   [1,2,3,4],
 *   [5,1,2,3],
 *   [9,5,1,2]
 * ]
 * Output: True
 * Explanation:
 * In the above grid, the diagonals are:
 * "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
 * In each diagonal all elements are the same, so the answer is True.
 *
 * @Date: 2019/7/4 19:47
 * @Version: 1.0
 */
public class IsToeplitzMatrix {

    public boolean solution(int[][] matrix) {
        //就是比較斜線上是否是通一個數據
        //每一斜線
        //每次可以和下一行的斜線比較,這樣依次比較
        for(int i = 0; i < matrix.length - 1; ++i) {
            for(int j = 0; j < matrix[i].length - 1; ++j) {
                if(matrix[i][j] != matrix[i + 1][j + 1]) {
                    return false;
                }
            }
        }
        return true;
    }


    public boolean isToeplitzMatrix(int[][] matrix) {
        for (int i = 0; i < matrix.length - 1; i++) {
            for (int j = 0; j < matrix[i].length - 1; j++) {
                if (matrix[i][j] != matrix[i + 1][j + 1]) return false;
            }
        }
        return true;
    }

    public static void main(String args[]) {

        int[][] matrix = {{1,2,3,4},{5,1,2,3},{9,5,1,2}};

        IsToeplitzMatrix fuc = new IsToeplitzMatrix();
        System.out.println(fuc.isToeplitzMatrix(matrix));
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章