766. Toeplitz Matrix

766. Toeplitz Matrix

题目描述

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:

1
2
3
4
5
6
7
8
9
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:

1
2
3
4
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
func isToeplitzMatrix(_ matrix: [[Int]]) -> Bool {
guard !matrix.isEmpty else { return false }
let width = matrix.count
let height = matrix[0].count
for (index, row) in matrix.enumerated() {
var i = index + 1, j = 1
let num = row[0]
while i < width && j < height {
if num != matrix[i][j] { return false }
i += 1
j += 1
}
}
for (index, column) in matrix[0].enumerated() {
guard index > 0 else { continue }
var i = 1, j = index + 1
let num = column
while i < width && j < height {
if num != matrix[i][j] { return false }
i += 1
j += 1
}
}
return true
}
}
0%