1.题目描述
这是字节的一道前端面试题。
给你一个二维数组,按照对角线的方式进行遍历。
2.举例
[
[1, 2],
[4, 5],
];
//输出 [1, 2, 4, 5]
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
// 输出 [1,2,4,3,5,7,6,8,9]
类似z
字形遍历
3.code 实现
/**
*
* @param {Array<Array>} arr
*/
function getResult(arr) {
let result = []; // 结果数组
let yLength = arr[0].length;
let xLength = arr.length;
let curPos = { x: 0, y: 0 }; // 当前的位置
let nextPos = { x: 0, y: 1 }; // 下一个跳转到位置
let isLoop = true; //是否循环
// 判断是否合法
const isLegal = (x, y) => {
return x >= 0 && x < xLength && y >= 0 && y < yLength;
};
// 判断是否是最后一个位置
const isLast = (x, y) => {
return x === xLength - 1 && y === yLength - 1;
};
while (isLoop) {
if (isLast(curPos.x, curPos.y)) {
isLoop = false;
}
result.push(arr[curPos.x][curPos.y]);
if (isLegal(curPos.x + 1, curPos.y - 1)) {
curPos = {
x: curPos.x + 1,
y: curPos.y - 1,
};
} else {
curPos = nextPos;
if (isLegal(curPos.x, curPos.y + 1)) {
nextPos = {
x: curPos.x,
y: curPos.y + 1,
};
} else if (isLegal(curPos.x + 1, curPos.y)) {
nextPos = {
x: curPos.x + 1,
y: curPos.y,
};
}
}
}
return result;
}
let matrix1 = [
[1, 2],
[4, 5],
];
let matrix2 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
let matrix3 = [
[1, 2, 3, 10],
[4, 5, 6, 11],
[7, 8, 9, 12],
];
console.log(getResult(matrix2));