漩涡型二维数组

作者:xie392地址:https://v.douyin.com/ieaCawgS/更新时间:2024-12-21

案例代码

1
/**
2
* 漩涡型二维数组
3
* @param {number} col
4
* @param {number} row
5
* @returns {Array} 二维数组
6
* @example
7
* 1 2 3 4
8
* 10 11 12 5
9
* 9 8 7 6
10
*/
11
function vortexMatrix(col, row) {
12
// 创建二维数组 初始值为0
13
const matrix = Array.from({ length: row }, () => Array.from({ length: col }, () => 0))
14
15
// 定义上下左右边界
16
let top = 0
17
let bottom = row - 1
18
let left = 0
19
let right = col - 1
20
21
// 定义当前位置
22
let current = 1
23
24
// 循环填充
25
while (current <= col * row) {
26
// 从左到右
27
for (let i = left; i <= right; i++) {
28
matrix[top][i] = current++
29
}
30
top++
31
32
// 从上到下
33
for (let i = top; i <= bottom; i++) {
34
matrix[i][right] = current++
35
}
36
right--
37
38
// 从右到左
39
for (let i = right; i >= left; i--) {
40
matrix[bottom][i] = current++
41
}
42
bottom--
43
44
// 从下到上
45
for (let i = bottom; i >= top; i--) {
46
matrix[i][left] = current++
47
}
48
left++
49
}
50
51
// 打印
52
matrix.forEach(row => {
53
console.log(row.join(' '))
54
})
55
56
return matrix
57
}
58
59
vortexMatrix(4, 3)

输出结果:

1
1 2 3 4
2
10 13 12 5
3
9 8 7 6