766. Toeplitz Matrix
Posted tobeabetterpig
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了766. Toeplitz Matrix相关的知识,希望对你有一定的参考价值。
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.? Example 1: 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. class Solution { public boolean isToeplitzMatrix(int[][] matrix) { // Check every diagonal starting from the nums on the border // Use a helper func to check every diagonal // Stop when out of boundary // Index I, j, the next element in this diagonal is I + 1, j + 1 // matrix = [ // [1,2,3,4], // [5,1,2,3], // [9,5,1,2] // ] // traverse from the top row, and the left col, check every starting point // coordinates for top row is : row is 0, col is from 0 to matrix[0].length // coordinates for the left col is , row is from 0 to matrix.length; col is 0 for(int j = 0; j < matrix[0].length; j++){ if(!helper(matrix, 0, j)) return false; } for(int i = 0; i < matrix.length; i++){ if(!helper(matrix, i, 0)) return false; } return true; } private boolean helper(int[][] matrix, int i, int j){ int num = matrix[i][j]; int row = i + 1; int col = j + 1; // check boundary and if boundary is valid, check if the next element has the same val as the cur if(row < 0 || col < 0 || row >= matrix.length || col >= matrix[0].length) return true; if(matrix[row][col] != num) return false; // keep dfs if(helper(matrix, row, col)){ return true; } return false; } }
以上是关于766. Toeplitz Matrix的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode-766-Toeplitz Matrix]