# LeetCode 766. Toeplitz Matrix

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:

1. matrix will be a 2D array of integers.
2. matrix will have a number of rows and columns in range [1, 20].
3. matrix[i][j] will be integers in range [0, 99].

return直接从函数中返回；

continue终止当前循环，从下一次循环开始执行；

break从循环中跳出。

class Solution {
public boolean isToeplitzMatrix(int[][] matrix) {
int m,n;
m = matrix.length;
n = matrix[0].length;

//int i =0;
for(int j=0; j<n; j++) {
int k=0,l=j;
while(k+1<m&& l+1<n) {
if(matrix[k][l] == matrix[k+1][l+1]) {
continue;
} else {
return false;
}
}

}// upper

//int j =0;
for(int i=0; i<m; i++) {
int k=i,l=0;
while(k+1<m && l+1<n) {
if(matrix[k][l] == matrix[k+1][l+1]) {
continue;
} else {
return false;
}
}

}// upper

return true;

/*matrix00 m11 m22
m01 m12 m23

m13
m23,

*/
}
}

Run Code Status: Time Limit Exceeded
Run Code Result:

[[1,2,3,4],[5,1,2,3],[9,5,1,2]]

true

Runtime: N/A

class Solution {
public boolean isToeplitzMatrix(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;

int[] array = new int[m*n];
/*for(int i=0; i<400; i++) {
array[i] = -1;
}*/

for(int i=0; i<m; i++) {
for(int j = 0; j<n; j++) {
array[i*n+j] = matrix[i][j];
}
}

//int
/*for(int i=0; i<400;i++) {
if(array[i] != -1) {
continue;
} else {

}
}*/

/* 1 3 5, 4 1 3, 2 4 1,
*/

}
}

class Solution {
public boolean isToeplitzMatrix(int[][] matrix) {

int m= matrix.length;
int n= matrix[0].length;

for(int i=0; i<m; i++){
for(int j=0; j<n; j++) {
if((0<i-1 && i-1<m)&&(0<j-1 && j-1<n)) {
if(matrix[i-1][j-1] != matrix[i][j]) {
return false;
}
}
}
}

return true;
}
}

结果：

Submission Result: Wrong Answer

Input: [[1,2],[2,2]]
Output: true

Expected: false

class Solution {
public boolean isToeplitzMatrix(int[][] matrix) {

int m= matrix.length;
int n= matrix[0].length;

for(int i=0; i<m; i++){
for(int j=0; j<n; j++) {
if(((0<=i-1) && (i-1<m))&&((0<=j-1) && (j-1<n))) {
if(matrix[i-1][j-1] != matrix[i][j]) {
return false;
}
}
}
}

return true;
}
}

结果：

#### Submission Result: Accepted

posted @ 2018-04-13 10:06  Zhao_Gang  阅读(110)  评论(0编辑  收藏  举报