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;
}