Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 766. Toeplitz Matrix

Rain Hu

766. Toeplitz Matrix


一、題目

Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false. A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.

Example 1:
ex1

Example 2: ex2

Constraints:

Follow up:


二、分析

三、解題

1. Simple traversal

bool isToeplitzMatrix(vector<vector<int>>& matrix) {
    int m = matrix.size(), n = matrix[0].size();
    for (int i = 1; i < m; i++) {
        for (int j = 1; j < n; j++) {
            if (matrix[i][j] != matrix[i-1][j-1]) return false;
        }
    }
    return true;
}

2. Follow up #1: load at most one row

bool isToeplitzMatrix(vector<vector<int>>& matrix) {
    deque<int> buffer;
    for (int j = 0; j < matrix[0].size()-1; j++) buffer.push_back(matrix[0][j]);    // 一次處理一行
    for (int i = 1; i < matrix.size(); i++) {
        for (int j = 1; j < matrix[0].size(); j++) {
            if (buffer.front() != matrix[i][j]) return false;
            buffer.pop_front();
            buffer.push_back(matrix[i][j]);
        }
        buffer.push_front(matrix[i][0]);
        buffer.pop_back();
    }
    return true;
}

3. Follow up #2: load partial row/column each time

bool isToeplitzMatrix(vector<vector<int>>& matrix) {
    int m = matrix.size(), n = matrix[0].size();
    queue<pair<int,int>> q;
    for (int i = m-1; i > 0; i--) q.push({i, 0});
    for (int i = 0 ; i < n; i++) q.push({0, i});
    while (!q.empty()) {
        auto info = q.front();
        q.pop();
        int row = info.first;
        int col = info.second;
        int val = matrix[row][col];
        while (++row < m && ++col < n) {
            if (matrix[row][col] != val) return false;
        }
    }
    return true;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 2269. Find the K-Beauty of a Number
Next
[LeetCode] 1016. Binary String With Substrings Representing 1 To N