forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain2.cpp
54 lines (42 loc) · 1.23 KB
/
main2.cpp
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/// Source : https://leetcode.com/problems/toeplitz-matrix/description/
/// Author : liuyubobobo
/// Time : 2018-01-26
#include <iostream>
#include <vector>
using namespace std;
/// Iterate all diagonal elements
/// Time Complexity: O(N^2)
/// Space Complexity: O(1)
class Solution {
public:
bool isToeplitzMatrix(vector<vector<int>>& matrix) {
for(int i = 0; i < matrix.size() ; i ++)
if(!ok(matrix, i, 0))
return false;
for(int j = 1 ; j < matrix[0].size() ; j ++)
if(!ok(matrix, 0, j))
return false;
return true;
}
private:
bool ok(const vector<vector<int>>& matrix, int i, int j){
int target = matrix[i][j];
while(i < matrix.size() && j < matrix[i].size()){
if(matrix[i][j] != target)
return false;
i ++;
j ++;
}
return true;
}
};
void printBool(bool res){
cout << (res ? "True" : "False") << endl;
}
int main() {
vector<vector<int>> matrix1 = {{1,2,3,4}, {5,1,2,3}, {9,5,1,2}};
printBool(Solution().isToeplitzMatrix(matrix1));
vector<vector<int>> matrix2 = {{1, 2}, {2, 2}};
printBool(Solution().isToeplitzMatrix(matrix2));
return 0;
}