# 托普利茲矩陣

## 範例檔案

1 2 3 4
5 1 2 3
9 5 1 2

1 2th Street, Suite XNUMX
2 2th Street, Suite XNUMX

1 2 3 4
5 1 2 3
9 5 1 2

## Toeplitz矩陣的JAVA代碼

```public class ToeplitzMatrix {
private static boolean isToeplitz(int[][] matrix) {
boolean ans = true;
int n = matrix.length;
int m = matrix[0].length;

// First row diagonals
for (int i = 0; i < m; i++) {
int x = 0, y = i;
int curr = matrix[x][y];
x++; y++;
while (x < n && y < m) {
// If any element is not same, this can't be a toeplitz matrix
if (matrix[x][y] != curr) {
ans = false;
break;
}
// Increment row and column by 1
x++; y++;
}
if (!ans)
break;
}

// First column diagonals
for (int i = 1; i < n; i++) {
int x = i, y = 0;
int curr = matrix[x][y];
x++; y++;
while (x < n && y < m) {
// If any element is not same, this can't be a toeplitz matrix
if (matrix[x][y] != curr) {
ans = false;
break;
}
// Increment row and column by 1
x++; y++;
}
if (!ans)
break;
}

return ans;
}

public static void main(String[] args) {
// Example 1
int[][] matrix = new int[][] {
{1, 2, 3, 4},
{5, 1, 2, 3},
{9, 5, 1, 2}};
System.out.println(isToeplitz(matrix));

// Example 2
int[][] matrix2 = new int[][] {
{1, 2},
{2, 2}
};
System.out.println(isToeplitz(matrix2));
}
}```

## Toeplitz矩陣的C ++代碼

```#include<bits/stdc++.h>
using namespace std;

int matrix[4][4];

bool isToeplitz(int n, int m) {
bool ans = true;

// First row diagonals
for (int i = 0; i < m; i++) {
int x = 0, y = i;
int curr = matrix[x][y];
x++; y++;
while (x < n && y < m) {
// If any element is not same, this can't be a toeplitz matrix
if (matrix[x][y] != curr) {
ans = false;
break;
}
// Increment row and column by 1
x++; y++;
}
if (!ans)
break;
}

// First column diagonals
for (int i = 1; i < n; i++) {
int x = i, y = 0;
int curr = matrix[x][y];
x++; y++;
while (x < n && y < m) {
// If any element is not same, this can't be a toeplitz matrix
if (matrix[x][y] != curr) {
ans = false;
break;
}
// Increment row and column by 1
x++; y++;
}
if (!ans)
break;
}

return ans;
}

int main() {
// Example 1
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[0][3] = 4;
matrix[1][0] = 5;
matrix[1][1] = 1;
matrix[1][2] = 2;
matrix[1][3] = 3;
matrix[2][0] = 9;
matrix[2][1] = 5;
matrix[2][2] = 1;
matrix[2][3] = 2;
if (isToeplitz(3, 4)) {
cout<<"true"<<endl;
} else {
cout<<"false"<<endl;
}

// Example 2
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[1][0] = 2;
matrix[1][1] = 2;
if (isToeplitz(2, 2)) {
cout<<"true"<<endl;
} else {
cout<<"false"<<endl;
}

return 0;
}```
```true
false```