isToeplitzMatrix-Toeplitz matrix

Title

Give you a matrix of mxn. If this matrix is ​​a Toplitz matrix, return true; otherwise, return false.

If the elements on each diagonal from the upper left to the lower right of the matrix are the same, then the matrix is ​​a Toplitz matrix.

Example 1:

Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: true
Explanation:
In the above matrix, its diagonal is :
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
All elements on each diagonal are the same, so the answer is True.

Example 2:

Input: matrix = [[1,2],[2,2]]
Output: false
Explanation:
The elements on the diagonal "[1, 2]" are different.

prompt:

m == matrix.length
n == matrix[i].length
1 <= m, n <= 20
0 <= matrix[i][j] <= 99

Problem-solving ideas

Here we divide this question into two parts according to the meaning of the question, one is the lower triangle (divided by 45° from each row to the lower right), the
second part, and the upper triangle (each column is divided by 45° to the lower right, excluding the first Column)
These two parts of judgment are basically the same. Take the following triangle as an example
. The coordinate judgment of the matrix, the lower right corner is compared with the upper left corner, that is, the abscissa plus one, the ordinate plus one
point in the current row and the point in each subsequent row if there is a difference then directly returns false
if the same, to the next line, repeating the previous step.

Code demo

class Solution {
    
    
    public boolean isToeplitzMatrix(int[][] matrix) {
    
    
        int m=matrix.length;
        int n=matrix[0].length;
          for(int i=0;i<m;i++)
          {
    
    
              int han=i+1;
              int lie=1;
              while (han<m&&lie<n)
              {
    
    
                  if(matrix[han][lie]!=matrix[han-1][lie-1])
                      return false;
                  han++;
                  lie++;
              }
          }
        for(int i=1;i<n;i++)
        {
    
    
            int lie=i+1;
            int han=1;
            while (han<m&&lie<n)
            {
    
    
                if(matrix[han][lie]!=matrix[han-1][lie-1])
                    return false;
                han++;
                lie++;
            }
        }
          return true;
    }
}

effect

The info
answer was successful:
execution time: 1 ms, defeating 100.00% of Java users
Memory consumption: 38.8 MB, defeating 11.67% of Java users

Guess you like

Origin blog.csdn.net/tangshuai96/article/details/113948481