输入一个自然数N(2≤N≤9),要求输出如下的魔方阵,即边长为N*N,元素取值为1至N*N,1在左上角,呈顺时针方向依次放置各元素。 N=3时:
1 2 3
8 9 4
7 6 5
【输入形式】 从标准输入读取一个整数N。
【输出形式】 向标准输出打印结果。输出符合要求的方阵,每个数字占5个字符宽度,向右对齐,在每一行末均输出一个回车符。
【输入样例】 4
【输出样例】
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
实现:
int col = 0;
int row = 0;
int counter = 1;
Direction d = Direction.RIGHT;
while( true ){
if( maze[row][col] == 0 ){
maze[row][col] = counter++;
switch (d) {
case RIGHT:
if( col + 1< n && maze[row][col + 1] == 0){
col ++;
}else{
d = Direction.DOWN;
row ++;
}
break;
case DOWN:
if( row + 1 < n && maze[row + 1][col] == 0){
row ++;
}else{
d = Direction.LEFT;
col --;
}
break;
case LEFT:
if( col - 1 >= 0 && maze[row][col-1] == 0){
col --;
}else{
d = Direction.UP;
row --;
}
break;
default:
if( row - 1 >= 0 && maze[row - 1][col] == 0){
row --;
}else{
d = Direction.RIGHT;
col ++;
}
break;
}
}else{
break;
}
}
return maze;
}
public void printMaze( int[][] maze ){
for( int[] row : maze ){
for( int i : row ){
System.out.printf("%3d", i);
}
System.out.println();
}
}
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please input the size of the maze:");
int size = sc.nextInt();
Maze maze = new Maze();
int[][] m = maze.buidMaze( size );
maze.printMaze( m );
}
}