Toeplitz Matrix Check
Problem
A Toeplitz matrix has the same value on every diagonal that goes from the top-left to the bottom-right. Print true if the matrix is Toeplitz, else false.
Constraints
- 1 <= r, c <= 500
Examples
Input
3 4 1 2 3 4 5 1 2 3 9 5 1 2
Output
true
Input
2 2 1 2 2 2
Output
false
Solutions
If every cell equals its top-left neighbour, then every diagonal is constant, because each diagonal is a chain of such neighbours. This needs no list of diagonals.
/*
* Problem : Process a matrix.
* Input : r and c, then r rows of c integers.
* Output : true or false.
* Approach: Compare with the top-left neighbour.
* Time : O(r * c)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static boolean solve(int[][] m) {
// Step 1: A cell must be equal to its neighbour at the top-left. Cells in the first row or first column have no such neighbour.
for (int i = 1; i < m.length; i++) {
for (int j = 1; j < m[0].length; j++) {
// Step 2: One difference on a diagonal is enough to decide.
if (m[i][j] != m[i - 1][j - 1]) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int cols = scanner.nextInt();
int[][] m = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
m[i][j] = scanner.nextInt();
}
}
System.out.println(solve(m));
}
}
Hints (1)
- Which cells have no top-left neighbour?