天天看點

LintCode 1042: Toeplitz Matrix

  1. 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

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.

Notice

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:

class Solution {
public:
    /**
     * @param matrix: the given matrix
     * @return: True if and only if the matrix is Toeplitz
     */
    bool isToeplitzMatrix(vector<vector<int>> &matrix) {
        int nRow = matrix.size();
        if (nRow == 0) return true;
        int nCol = matrix[0].size();
        if (nCol == 0) return true;

        for (int i = 0; i < nRow; ++i) {
            int firstElem = matrix[i][0];
            int row = i;
            int col = 0;
            while (row < nRow - 1 && col < nCol - 1) {
                row++;
                col++;
                if (matrix[row][col] != firstElem) return false;
            }
        }
        
        for (int j = 1; j < nCol; ++j) {
            int firstElem = matrix[0][j];
            int row = 0;
            int col = j;
            while (row < nRow - 1 && col < nCol - 1) {
                row++;
                col++;
                if (matrix[row][col] != firstElem) return false;
            }
        }
        
        return true;
    }
};
           

繼續閱讀