码迷,mamicode.com
首页 > 其他好文 > 详细

766. Toeplitz Matrix

时间:2018-09-20 18:49:37      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:nts   i++   length   inpu   OLE   eve   ||   int   each   

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

标签:nts   i++   length   inpu   OLE   eve   ||   int   each   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9682529.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!