Daily Coding Problem: Problem #315

Posted johnnyzhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Daily Coding Problem: Problem #315相关的知识,希望对你有一定的参考价值。

/**
 * This problem was asked by Google.

In linear algebra,
a Toeplitz matrix is one in which the elements on any given diagonal from top left to bottom right are identical.

Here is an example:
1 2 3 4 8
5 1 2 3 4
4 5 1 2 3
7 4 5 1 2
Write a program to determine whether a given input is a Toeplitz matrix.
 * */
class Problem_315 
    fun isToeplitz(): Boolean 
        //5行4列的matrix
        var mat = arrayOf(
            intArrayOf(6, 7, 8, 9),
            intArrayOf(4, 6, 7, 8),
            intArrayOf(1, 4, 6, 7),
            intArrayOf(0, 1, 4, 6),
            intArrayOf(2, 0, 1, 4)
        )

        /*mat = arrayOf(
            intArrayOf(6, 3, 8),
            intArrayOf(4, 9, 7),
            intArrayOf(1, 4, 6)
        )*/

        val row = mat.size
        val col = mat[0].size

        //check begin from row
        for (i in 0..(row - 1)) 
            if (!checkDiagonal(mat, i, 0)) 
                return false
            
        
        //check begin from col
        for (i in 0..(col - 1)) 
            if (!checkDiagonal(mat, 0, i)) 
                return false
            
        

        return true
    

    private fun checkDiagonal(matrix: Array<IntArray>, i_: Int, j_: Int): Boolean 
        val row = matrix.size
        val col = matrix[0].size
        var i = i_
        var j = j_
        val res = matrix[i][j]
        while (++i < row && ++j < col) 
            if (matrix[i][j] != res) 
                return false
            
        
        return true
    

 

以上是关于Daily Coding Problem: Problem #315的主要内容,如果未能解决你的问题,请参考以下文章

[Daily Coding Problem 290] Quxes Transformation

[Daily Coding Problem 250] Cryptarithmetic Puzzle

[Daily Coding Problem 70] Nth perfect number

[Daily Coding Problem 68] Count Pairs of attacking bishop pairs

[Daily Coding Problem 24] Implement locking in a binary tree.

[Daily Coding Problem 294] Shortest round route with rising then falling elevations