/** * 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 } }
原文地址:https://www.cnblogs.com/johnnyzhao/p/11108508.html
时间: 2024-10-09 10:00:02