题目
“””
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:
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].
“””
思路
这道题其实就是一个搜索问题,怎么去搜索?搜索的边界如何确定?这就是解决问题的关键。比如说题目的例子
1 | [[1,2,3,4], |
实际上就是对角线去搜索元素是否相同就可以。一种做法是从第一行开始对角元素遍历,将遍历过的元素全部置为-1,表示已经访问过的元素,当第一行遍历完成后转向第二行开始遍历,同时注意遍历的边界——一个矩阵的行列;遍历过程如下:
1 | 第一轮 (''号代表第一轮访问) |
这种做法是最普通的,但也是最耗时的,因为在第一行进行第一轮的对角元素遍历后,再从第二行开始对角元素遍历时,实际上会遍历在刚刚第一轮就已经遍历过的元素,做了许多无用功。因此,重新观察矩阵之后,可以知道,只需要从第一行和第一列进行对角元素遍历就可以解决了,这就是第二种方法,相比于第一种方法,避免做了无用的访问。
解题代码
1 | class Solution(object): |