/**
* 蛇形排列的算法實現
*
* 蛇形排列
*
* 輸入4
* 輸出:
* 1 2 3 4
* 12 13 14 5
* 11 16 15 6
* 10 9 8 7
*
* 輸入5:
*
* 1 2 3 4 5
* 16 17 18 19 6
* 15 24 25 20 7
* 14 23 22 21 8
* 13 12 11 10 9
*/
package com.my.alg;
import java.io.*;
import java.util.*;
public class SnakeSort {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
int[][] arr = new int[i][i];
snakeSort(arr);
//打印
for(int m = 0;m < i; m ++){
for(int n = 0; n < i; n ++){
System.out.print(arr[m][n] + " ");
}
System.out.println();
}
}
public static void snakeSort(int[][] a){
int i = a.length;//數組的邊
int increase = 1;//從一開始計數
int now = 0;//循環次數
int which = 0;//標記這是第幾層,有外到內,0 1 2....
//從最外層開始排列
while(now < i){
//上面的橫排填充
for(int k = 0 + which;k < i - which; k ++){
System.out.println(which + " " + k);
a[which][k] = increase;
increase ++;
}
//右側的豎排填充
for(int k = which + 1 ; k < i - which; k++){
System.out.println(k + " " + (i - which -1));
a[k][i - which -1] = increase;
increase ++;
}
//下面的橫排填充
for(int k = i - 2 -which ; k >=which ; k --){
System.out.println((i - which -1) + " " + k);
a[i-1 - which][k] = increase;
increase ++;
}
//左側的豎排填充
for(int k = i - 2 -which ; k > which ; k --){
System.out.println(k + " " + which);
a[k][which] = increase;
increase ++;
}
//層數加一
which ++;
//進行下一個循環
now += 2;
}
}
}
蛇形排列 非遞歸
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.