您的位置:首页 > 其它

蛇形排列 非递归

2012-08-12 16:12 239 查看
/**
* 蛇形排列的算法实现
*
* 蛇形排列
*
* 输入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]
+ "       ");
}
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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  import string class 算法