Skip to content

Instantly share code, notes, and snippets.

@ony19161
Created November 3, 2022 04:46
Show Gist options
  • Save ony19161/86b81db9c5d4cea2e44a73ecc48b560f to your computer and use it in GitHub Desktop.
Save ony19161/86b81db9c5d4cea2e44a73ecc48b560f to your computer and use it in GitHub Desktop.
toeplitz-matrix-solved
bool isMatchingDiagonalValues(vector<vector<int>>& matrix, int x, int y, int limit, bool isBottomHalf)
{
bool isMatching = true;
if (isBottomHalf)
{
if (x > limit)
return true;
while (y < matrix[0].size() - 1 && x <= limit)
{
if (matrix[x][y] != matrix[x + 1][y + 1])
{
return false;
}
x++;
y++;
}
}
else
{
if (y > limit)
return true;
while (x < matrix.size() - 1 && y <= limit)
{
if (matrix[x][y] != matrix[x + 1][y + 1])
{
return false;
}
x++;
y++;
}
}
return isMatching;
}
bool isToeplitzMatrix(vector<vector<int>>& matrix) {
bool isToeplizMatrixFound = true;
int rows = matrix.size();
int columns = matrix[0].size();
if (rows == 1 || columns == 1)
{
isToeplizMatrixFound = true;
}
else
{
for (int i = 0; i < rows - 1; i++)
{
if (i < columns - 1 && matrix[i][i] != matrix[i + 1][i + 1])
{
isToeplizMatrixFound = false;
break;
}
}
if (isToeplizMatrixFound)
{
int startIndex;
startIndex = 1;
while (startIndex < rows - 1)
{
if (isMatchingDiagonalValues(matrix, startIndex, 0, rows - 2, true))
{
startIndex++;
}
else
{
isToeplizMatrixFound = false;
break;
}
}
if (isToeplizMatrixFound)
{
startIndex = 1;
while (startIndex < columns - 1)
{
if (isMatchingDiagonalValues(matrix, 0, startIndex, columns - 2, false))
{
startIndex++;
}
else
{
isToeplizMatrixFound = false;
break;
}
}
}
}
}
return isToeplizMatrixFound;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment