LeetCode Ts-766. Toeplitz Matrix

    CodingLeetCode Js-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.

    給予一個 m x n 的矩陣,如果矩陣中「每條從左上到右下的對角線」上的元素都相同,則回傳 true,否則回傳 false。
    

    Example 1:

    Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
    Output: true
    Explanation:
    In the above grid, the diagonals are:
    "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
    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.
    

    Solution:
    這題要能理解如何從二維陣列中取出數值來進行比對,
    再來就是遍歷矩陣中的陣列元素,
    如果左上與右下相同則繼續直到結束回傳 true,否則回傳 false。

    Code 1: BigO(m * n)

    function isToeplitzMatrix(matrix: number[][]): boolean { 
        for (let i = 1; i < matrix.length; i++) {
            for (let j = 1; j < matrix[i].length; j++) {
                if (matrix[i][j] !== matrix[i - 1][j - 1]) {
                    return false;
                }
            }
        }
        return true;
    };
    

    FlowChart:
    Example 1

    Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
    
    matrix[i][j] 1, matrix[i - 1][j - 1] 1 // continue;
    matrix[i][j] 2, matrix[i - 1][j - 1] 2 // continue;
    matrix[i][j] 3, matrix[i - 1][j - 1] 3 // continue;
    matrix[i][j] 5, matrix[i - 1][j - 1] 5 // continue;
    matrix[i][j] 1, matrix[i - 1][j - 1] 1 // continue;
    matrix[i][j] 2, matrix[i - 1][j - 1] 2 // continue;
    
    return true;
    

    Example 2

    Input: matrix = [[1,2],[2,2]]
    
    matrix[i][j] 2, matrix[i - 1][j - 1] 1 // false
    
    return false;