实现螺旋数组
// 1 2 3 4// 10 11 12 5// 9 8 7 6// row 行数// col 列数constcreateVortexArr=(row,col)=>{// 创建二维数组constarr=newArray(row);for(leti=0;i<row;i++){arr[i]=newArray(col).fill(0);}letnum=1;// 填入的值letmaxNum=row*col;// 填入的最大值letx=0;lety=0;letminX=0;letminY=1;letmaxX=col-1;letmaxY=row-1;letstepX=1;letstepY=0;while(true){arr[y][x]=num;num++;if(num>maxNum)break;x+=stepX;y+=stepY;if(stepX==1){if(x==maxX){stepX=0;stepY=1;}}if(stepX==-1){if(x==minX){stepX=0;stepY=-1;}}if(stepY==1){if(y==maxY){stepX=-1;stepY=0;}}if(stepY==-1){if(y==minY){stepX=1;stepY=0;// 如果到达了 minY,说明走完了一圈minX++;minY++;maxX--;maxY--;}}}returnarr;};
constres=createVortexArr(6,7);for(letitemofres){console.log(item);}
(7) [1, 2, 3, 4, 5, 6, 7] (7) [22, 23, 24, 25, 26, 27, 8] (7) [21, 36, 37, 38, 39, 28, 9] (7) [20, 35, 42, 41, 40, 29, 10] (7) [19, 34, 33, 32, 31, 30, 11] (7) [18, 17, 16, 15, 14, 13, 12]