• 766. Toeplitz Matrix


    问题:

    给定一个二维数组,

    若该数组的所有方向的对角线数值相同,则为Toeplitz矩阵,返回true,否则返回false

    Example 1:
    Input:
    matrix = [
      [1,2,3,4],
      [5,1,2,3],
      [9,5,1,2]
    ]
    Output: True
    Explanation:
    In the above grid, the diagonals are:
    "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
    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:
    matrix will be a 2D array of integers.
    matrix will have a number of rows and columns in range [1, 20].
    matrix[i][j] will be integers in range [0, 99].
    

      

    解法:

    i从1开始,j从1开始,

    只要当前元素==[i-1] [j-1] (其左上角元素)一直到遍历结束,都满足,则满足条件。返回true。

    只要其中一次不满足,则返回false

    代码参考:

     1 class Solution {
     2 public:
     3     bool isToeplitzMatrix(vector<vector<int>>& matrix) {
     4         int n = matrix.size(), m = matrix[0].size();
     5         for(int i=1; i<n; i++){
     6             for(int j=1; j<m; j++){
     7                 if(matrix[i][j]!=matrix[i-1][j-1]) return false;
     8             }
     9         }
    10         return true;
    11     }
    12 };
  • 相关阅读:
    hdu 4002 Find the maximum
    hdu 2837 坑题。
    hdu 3123
    zoj Treasure Hunt IV
    hdu 2053 Switch Game 水题一枚,鉴定完毕
    poj 1430 Binary Stirling Numbers
    hdu 3037 Saving Beans
    hdu 3944 dp?
    南阳oj 求N!的二进制表示最低位的1的位置(从右向左数)。
    fzu 2171 防守阵地 II
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/12835975.html
Copyright © 2020-2023  润新知