var arr = [[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20],
[21,22,23,24,25]]
就这么一个二维数组,如何从 arr[0][0]开始从外圈顺时针旋转输出每一个数字?
//快速生成 n*n 的二维数组
let arr = [];
let num = 6;
for(let i=0;i<num*num;i++){
let index = parseInt(i/num);
if(!arr[index]){
arr[index] = [];
}
arr[index][i%num] = i;
}
//算法
order(arr){
let rs = [];
//边长
let length = arr[0].length;
//圈数
let circle = 0;
//四个方向 right down left top
let direction = ['r','d','l','t'];
//用这个参数控制方向
let dir_index = 0;
//计数器
let counts = 0;
// x y 坐标
let x = 0;
let y = 0;
while(true){
let shouleCounts = length - 1 - circle*2;
if(rs.length >= length*length){
break;
}
//每圈的开始主动把第一个元素放进来
if(counts == 0){
x = circle;
y = circle;
rs.push(arr[x][y]);
console.log(x,y);
y++;
counts++;
continue;
}
//基数行最后一圈特殊,只有一个元素,放进来结束掉
if(length%2 == 1 && circle == (length+1)/2){
rs.push(arr[circle-1][circle-1]);
break;
}
//控制方向
if(counts%shouleCounts == 0 || counts == shouleCounts*4-1){
dir_index++;
if(dir_index == 4){
dir_index = 0;
}
}
console.log(x,y);
rs.push(arr[x][y]);
//添加完后,开始变化坐标
if(direction[dir_index] == 'r'){
y++;
}else if(direction[dir_index] == 'd'){
x++;
}else if(direction[dir_index] == 'l'){
y--;
}else if(direction[dir_index] == 't'){
x--;
}
//控制每圈的循环次数,循环完毕后重置数据,进入下一圈循环
if(counts == 4*shouleCounts-1){
counts = 0;
circle++;
}
//第一个元素要特殊处理,特殊处理中已经 count++
if(counts>0){
counts++;
}
}
return rs;
}
网友评论