运行环境
- 系统:Win10系统
- IDE:
Visual Studio Code v1.79.2
- VSCode插件:
Code Runner v0.12.0
算法一、逐层计算算法
从最外圈开始计算,没计算一圈,限制范围缩小一圈,每一圈计算步骤:
- (左上)到(右上-1)
- (右上)到(右下-1)
- (右下)到(左下-1)
- (右下-1)到(左上-1)
index.js
function vortex(n, m) {
const nums = new Array(n).fill(0).map(() => new Array(m).fill(0));
let i = 0, imin = 0, imax = m, j = 0, jmin = 0, jmax = n
let curNum = 0, layer = 0, count = m * n;
while (curNum < count) {
//(左上)到(右上-1)
while (i < imax - 1 && curNum <= count) {
nums[j][i] = ++curNum; i++;
}
//(右上)到(右下-1)
while (j < jmax - 1 && curNum <= count) {
nums[j][i] = ++curNum; j++;
}
//(右下)到(左下-1)
while (i > imin && curNum <= count) {
nums[j][i] = ++curNum; i--;
}
//(右下-1)到(左上-1)
while (j > jmin && curNum <= count) {
nums[j][i] = ++curNum; j--;
}
//圈数 //设置每一圈的起始点
layer++;i = layer; j = layer;
//范围减一圈
imax--; jmax--; imin++; jmin++;
}
return nums;
}
console.log(vortex(5, 6));
输出
[Running] node "e:\MD\katex\index.js"
[
[ 1, 2, 3, 4, 5, 6 ],
[ 18, 19, 20, 21, 22, 7 ],
[ 17, 28, 29, 30, 23, 8 ],
[ 16, 27, 26, 25, 24, 9 ],
[ 15, 14, 13, 12, 11, 10 ]
]
[Done] exited with code=0 in 0.211 seconds
算法一、避障转弯计算
移动,判断障碍,如果有障碍则转弯,没有障碍继续当前的步调往前走。障碍有两种:
- 越界:x方向小于0大于x长度;y方向小于0大于y长度。
- 已走:已经走过的格子填完数字(非0)的格子
index.js
function vortex(n, m) {
const nums = new Array(n).fill(0).map(() => new Array(m).fill(0));
let i = 0, j = 0, stepi = 1, stepj = 0;
let count = 1;
//是否有障碍
function hasBlock() {
return !nums[j] || nums[j][i] !== 0;
}
while (1) {
nums[j][i] = count++;
//改动i和j
i += stepi;
j += stepj;
if (hasBlock()) {
i -= stepi;
j -= stepj;
//转弯
if (stepj === 0) {
stepj = stepi;
stepi = 0;
}
else {
stepi = -stepj;
stepj = 0;
}
i += stepi;
j += stepj;
}
if (hasBlock()) {
break;
}
}
return nums;
}
console.log(vortex(5, 6));
输出
[Running] node "e:\MD\katex\index.js"
[
[ 1, 2, 3, 4, 5, 6 ],
[ 18, 19, 20, 21, 22, 7 ],
[ 17, 28, 29, 30, 23, 8 ],
[ 16, 27, 26, 25, 24, 9 ],
[ 15, 14, 13, 12, 11, 10 ]
]
[Done] exited with code=0 in 0.272 seconds