/**
* 蛇形排列的算法实现
*
* 蛇形排列
*
* 输入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;
}
}
}
蛇形排列 非递归
最新推荐文章于 2024-07-20 16:51:44 发布