# 766.Toeplitz Matrix

**766.Toeplitz Matrix**

难度:Easy

> 如果一个矩阵的每一方向由左上到右下的对角线上具有相同元素，那么这个矩阵是托普利茨矩阵。

给定一个 M x N 的矩阵，当且仅当它是托普利茨矩阵时返回 True。

```
示例 1:

输入: 
matrix = [
  [1,2,3,4],
  [5,1,2,3],
  [9,5,1,2]
]
输出: True
解释:
在上述矩阵中, 其对角线为:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]"。
各条对角线上的所有元素均相同, 因此答案是True。
示例 2:

输入:
matrix = [
  [1,2],
  [2,2]
]
输出: False
解释: 
对角线"[1, 2]"上的元素不同。
说明:

 matrix 是一个包含整数的二维数组。
matrix 的行数和列数均在 [1, 20]范围内。
matrix[i][j] 包含的整数在 [0, 99]范围内。
```

进阶:

如果矩阵存储在磁盘上，并且磁盘内存是有限的，因此一次最多只能将一行矩阵加载到内存中，该怎么办？ 如果矩阵太大以至于只能一次将部分行加载到内存中，该怎么办？

方法：该矩阵特点在于下一行第二位开始实际上是上一行向右平移移位得到的，因此只需要连续比较两行即可。

```
class Solution {
public:
    bool isToeplitzMatrix(vector<vector<int>>& matrix) {
        if(matrix.size()<=1) return true;
        for(int i=0;i<matrix.size()-1;i++)
        {
            vector<int> row1(matrix[i].begin(),matrix[i].end()-1);
            vector<int> row2(matrix[i+1].begin()+1,matrix[i+1].end());
            if(row1 != row2) return false;
        }
        return true;
    }
};
```

或者将`row1`和`row2`的类型改为string，可以减少一点内存消耗，但会增加一点时间。\
如果矩阵太大，每次只能加载一行，则每次将上一行右移一位的结果保存，然后输入时候比较。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/766.toeplitz_matrix.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
