蛇形排列 非递归
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; } } }
相关文章推荐
- 递归求解全排列
- 【C语言】编写一个函数reverse_string(char * string)(递归实现),将参数字符串中的字符反向排列,不能使用C函数库中的字符串操作函数。
- 祝福:新春新年大吉大利。问鼎天下,谁与争锋。非递归非交换非转数组非无序全排列组合算法,诚邀比、测、评。
- 递归--数字(字母)排列问题
- UVa 10344 - 23 out of 5 全排列递归回溯
- 全排列,递归实现
- C 递归排列
- 全排列(交换,递归,有详细解释)
- 13_栈的递归实例4---全排列
- 排列与组合的Java递归实现 (参考)
- 全排列非递归
- 递归全排列学习笔记
- 全排列方法一(递归)
- 递归方法的使用之一 -- 用递归进行排列组合
- 递归--全排列
- 递归输出一组元素的排列组合方式
- //4. 编写一个函数reverse_string(char * string)(递归实现) //实现:将参数字符串中的字符反向排列。 //要求:不能使用C函数库中的字符串操作函数。
- 用递归的方法判断整数组a[N]是不是升序排列
- 蓝桥杯 第三课 排列组合与递归
- 玩玩递归1--Fib,排列,与组合