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]
.
這道題讓我們驗證一個矩陣是否是托普利茲矩陣Toeplitz Matrix,所謂的這個托普利茲矩陣,就是看每條從左上到右下的對角線是否是值都相等。注意矩陣的行數列數不一定相等,要驗證所有的對角線。那么其實這道題的本質是讓我們斜向遍歷矩陣,就是按對角線來。那么博主最先想到的方法就是按照對角線來遍歷矩陣,起點是最左下的數字,對於mxn的矩陣,最左下角數字的坐標為(m-1, 0),然后我們開始往右下角遍歷,我們先記錄每條對角線左上角的數字為val,然后再往右下角遍歷的時候,如果同一條對角線上的數字不等於val,直接返回false。當我們遍歷完一條對角線的時候,切換一條對角線的時候,是根據起點數字的坐標移動的,如果細心觀察會發現,起點位置是先從第一列往上移動,然后在第一行往右移動,那么只要根據起點位置的行坐標是否為0來判斷移動的方向即可,比如對於題目中的例子1:
1 2 3 4
5 1 2 3
9 5 1 2
起點移動的方向是9 -> 5 -> 1 -> 2 -> 3 -> 4,參見代碼如下:
解法一:
class Solution { public: bool isToeplitzMatrix(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(), p = m - 1, q = 0; while (p >= 0 && q < n) { int val = matrix[p][q], i = p, j = q; while (i + 1 < m && j + 1 < n) { if (matrix[++i][++j] != val) return false; } (p > 0) ? --p : ++q; } return true; } };
其實並不需要像上面解法寫的那么復雜,我們還可以按正常順序來遍歷數組,對於每個遍歷到的數字,都跟其右下方的數字對比,如果不相同,直接返回false即可。為了防止越界,我們不遍歷最后一行和最后一列,遍歷完成后,返回true,參見代碼如下:
解法二:
class Solution { public: bool isToeplitzMatrix(vector<vector<int>>& matrix) { for (int i = 0; i < matrix.size() - 1; ++i) { for (int j = 0; j < matrix[i].size() - 1; ++j) { if (matrix[i][j] != matrix[i + 1][j + 1]) return false; } } return true; } };
類似題目:
參考資料:
https://leetcode.com/problems/toeplitz-matrix/discuss/113417/Java-solution-4-liner.