`

螺旋数字

    博客分类:
  • java
阅读更多
来源于 http://hi.baidu.com/shijiebei_2009/item/3629962d7056e50043634a69

以该数字为矩阵的大小,把1,2,3…n*n 的数字按照顺时针螺旋的形式填入其中
import java.util.Scanner;
 
/**
 * 从键盘输入一个整数(1~20)
则以该数字为矩阵的大小,把1,2,3…n*n 的数字按照顺时针螺旋的形式填入其中。例如:
输入数字2,则程序输出:
1 2
4 3
输入数字3,则程序输出:
1 2 3
8 9 4
7 6 5
输入数字4, 则程序输出:
1  2   3   4
12  13  14  5
11  16  15  6
10   9  8   7
 * 
 * @author wangxu
 * date:2012/3/24
 * 说明:时间有限,给一个不太优化的代码,足以实现功能
 * 思路:先声明一个二维数组用来存储每个对应的数字,对数组赋值完成之后就可以打印输出
 * 我的代码可以实现整型以内的所有合法数字,并不局限于20以内
 * 
 */
public class Demo {
static int arr[][];//二维数组用来存储数字
static int currentNumber = 1;// 从1开始打印,用来控制整个流程需要打印的数字
static int num = 0;//用来判断何时可以打印
public static void main(String args[]) throws Exception {
Scanner in = new Scanner(System.in);//获取输入流
System.out.println("请输入您希望打印的矩阵的最大的值:");//打印提示信息
String input = in.next();//获取用户的输入
int count = 0;//计数器
if (input.matches("\\d+")) {// 输入正确,用来检验用户输入的是否是数字
num = Integer.parseInt(input);
count = num;// count用来控制在每一个方向上打印几个数字,第一次打印时候和用户输入的数字相同
} else {
System.out.println("您输入的数据不正确,系统推出!");
System.exit(0);
}
arr = new int[num][num];//实例化数组
moveRight(count, 0, 0);//调用右移函数
}
 
public static void moveRight(int count, int rowIndex,
int columnIndex) {//count表示移动几步,由题目可以看出右移时候次数和是用户输入的数字,下移减1,左移不变,上移减1,右移不变
if(judge()){//如果数组已经赋值结束,就打印出来
print();
}else{
int temp = 0;//临时变量
while (temp < count) {
arr[rowIndex][columnIndex] = currentNumber;
temp ++;//临时变量自增
columnIndex++;//向右移动
currentNumber++;//当前要打印的数字自增
}
count--;//将打印次数减1
columnIndex--;//下标归位
rowIndex++;//下移一位
moveDown(count,rowIndex,columnIndex);
}
}
 
public static void moveDown(int count,int rowIndex,int columnIndex) {
if(judge()){
print();
}else{
int temp = 0;
while(temp < count){
arr[rowIndex][columnIndex] = currentNumber;
temp ++;
rowIndex++;
currentNumber++;
}
rowIndex--;
columnIndex--;//左移一位
moveLeft(count, rowIndex, columnIndex);
}
 
}
 
public static void moveLeft(int count,int rowIndex,int columnIndex) {
if(judge()){
print();
}else{
int temp = 0;//临时变量
while(temp < count){
arr[rowIndex][columnIndex]=currentNumber;
temp ++;
columnIndex--;//左移一位
currentNumber++;//数字自增
}
count--;//次数减1
columnIndex++;
rowIndex--;//上移一位
moveUp(count, rowIndex, columnIndex);
 
}
}
 
public static void moveUp(int count,int rowIndex,int columnIndex) {
if(judge()){
print();
}else{
 
int temp = 0;
while(temp < count){
arr[rowIndex][columnIndex] = currentNumber;
temp ++;
rowIndex--;
currentNumber++;
}
rowIndex++;
columnIndex++;//右移一位
moveRight(count, rowIndex, columnIndex);
}
 
}
public static void print(){//在控制台打印
for(int row[]:arr){
for(int column:row){
System.out.print(column+"\t");
}
System.out.println();//换行打印
}
}
public static boolean judge(){
if(currentNumber>Math.pow(num, 2)){//如果数组已经赋值结束,就打印出来
return true;
}else{
return false;
}
}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics