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: 1234 5123 9512 In the above grid, the diagonals are "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]", and 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:
matrixwill be a 2D array of integers.matrixwill have a number of rows and columns in range[1, 20].matrix[i][j]will be integers in range[0, 99].
解题思路:
多重循环比较,感觉没有什么难点,不知道有没有更简单的方法。
1 class Solution { 2 public: 3 bool isToeplitzMatrix(vector<vector<int>>& matrix) { 4 int row = matrix.size(); 5 int column = matrix[0].size(); 6 7 for (int i = 0; i < row; i++) { 8 for (int j = 0; j < column; j++) { 9 for (int m = i + 1, n = j + 1; m < row && n < column; m++, n++) { 10 if (matrix[i][j] != matrix[m][n]) { 11 return false; 12 } 13 } 14 } 15 } 16 17 return true; 18 } 19 };