题目描述
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.
给的用例
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.
题目说明
就是数字矩阵的斜线上的元素要相等,其实看用例就能看出来
我的代码
/**
* @param {number[][]} matrix
* @return {boolean}
*/
var isToeplitzMatrix = function(matrix) {
//这里把二维数组转成一维数组,这样所谓的斜线元素其实就是当前元素往后移动每行的元素个数再加1的那个元素,
//但要注意二维数组每行的最后一个元素不需要判断,我觉得这样搞好理解一些
var colLength = matrix[0].length;
var newArray = [].concat.apply([],matrix); // 二维转一维
for(var index = 0; index < newArray.length - colLength; index++)
{
if((index + 1) % colLength == 0) continue; // 这里的作用是排除二维数组中每行的最后一个元素,它对应的一维数组的写法就是这样
if(newArray[index] != newArray[index + colLength + 1])
{
return false;
}
}
return true;
};