Given an m x n
matrix, return true
if the matrix is a Toeplitz Matrix. A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.
true
by convention.(i,j)
, compare it with the element at position (i+1, j+1)
.false
.true
.Here’s a possible implementation in C++:
#include <vector>
using namespace std;
class Solution {
public:
bool isToeplitzMatrix(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
for (int i = 0; i < m - 1; ++i) {
for (int j = 0; j < n - 1; ++j) {
if (matrix[i][j] != matrix[i+1][j+1]) {
return false;
}
}
}
return true;
}
};
m
is the number of rows and n
is the number of columns. This is because every element (excluding the last row and column) is checked once.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?