打印螺旋矩阵逻辑中的逻辑问题



我试图解决螺旋矩阵问题,但我的逻辑遇到了一些问题。下方的代码

const arr = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
function spiralOrderMatrix(arr) {
let top = 0;
let left = 0;
let right = arr[0].length - 1;
let bottom = arr.length - 1;
let result = [];

while(top <= bottom && left <= right) {
for(let i = left; i <= right; i++) {
result.push(arr[top][i]);
console.log(arr[top][i], '----top');
}
top++;
for(let j = top; j <= bottom; j++) {
result.push(arr[j][right]);
console.log(arr[j][right], '----Right');
}
right--;
for(let k = right; k >= left; k--) {
result.push(arr[bottom][k]);
console.log(arr[bottom][k], '----Bottom');
}
bottom--;
for(let l = bottom; l >= top; l--) {
result.push(arr[l][left]);
console.log(arr[l][left], '----left');
}
left++;
} 
console.log(result);
}
spiralOrderMatrix(arr);

预期输出:[1,2,3,4,8,12,11,10,9,5,6,7]实际输出:[1,2,3,4,8,12,11,10,9,5,6,7,6]

对于底部和左侧的结果推送,如果检查顶部的条件小于等于底部,则添加

const arr = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
function spiralOrderMatrix(arr) {
let top = 0;
let left = 0;
let right = arr[0].length - 1;
let bottom = arr.length - 1;
let result = [];
while (top <= bottom && left <= right) {
for (let i = left; i <= right; i++) {
result.push(arr[top][i]);
console.log(arr[top][i], '----top');
}
top++;
for (let j = top; j <= bottom; j++) {
result.push(arr[j][right]);
console.log(arr[j][right], '----Right');
}
right--;
if (top <= bottom) {
for (let k = right; k >= left; k--) {
result.push(arr[bottom][k]);
console.log(arr[bottom][k], '----Bottom');
}
}
bottom--;
if (top <= bottom) {
for (let l = bottom; l >= top; l--) {
result.push(arr[l][left]);
console.log(arr[l][left], '----left');
}
}
left++;
}
console.log(result);
}
spiralOrderMatrix(arr);

参考编号:https://gist.github.com/lienista/af013a6425eaf781cbc659474f0b91b6

最新更新