766. Toeplitz Matrix

问题:

给定一个二维数组,

若该数组的所有\方向的对角线数值相同,则为Toeplitz矩阵,返回true,否则返回false

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.

Example 2:
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].

  

解法:

i从1开始,j从1开始,

只要当前元素==[i-1] [j-1] (其左上角元素)一直到遍历结束,都满足,则满足条件。返回true。

只要其中一次不满足,则返回false

 

代码参考:

 1 class Solution {
 2 public:
 3     bool isToeplitzMatrix(vector<vector<int>>& matrix) {
 4         int n = matrix.size(), m = matrix[0].size();
 5         for(int i=1; i<n; i++){
 6             for(int j=1; j<m; j++){
 7                 if(matrix[i][j]!=matrix[i-1][j-1]) return false;
 8             }
 9         }
10         return true;
11     }
12 };

 

posted @ 2020-05-06 13:55  habibah_chang  阅读(151)  评论(0编辑  收藏  举报