aboutsummaryrefslogtreecommitdiff
path: root/store/works/solutions/leetcode/cpp/766.cpp
blob: 3e8a01561d22f18def2ec51e63529ac9d6d29434 (plain)
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
#include <algorithm>
#include <vector>

using std::vector;

class Solution {
public:
  bool isToeplitzMatrix(vector<vector<int>> &matrix) {
    int row_count = matrix.size();
    int col_count = matrix.front().size();

    if (matrix.size() == 1)
      return true;
    if (matrix.front().size() == 1)
      return true;

    // offset = col - row
    // max(offset) = row_count - 2
    // min(offset) = -(col_count - 2)
    for (int offset = -(col_count - 2); offset <= (row_count - 2); offset++) {
      int row, col;
      if (offset >= 0) {
        row = offset;
        col = 0;
      } else {
        row = 0;
        col = -offset;
      }

      int value = matrix[row][col];
      row++;
      col++;

      while (row < row_count && col < col_count) {
        if (matrix[row][col] != value) {
          return false;
        }
        row++;
        col++;
      }
    }
    return true;
  }
};