輸入一個自然數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
實現:
package cn.dfeng; import java.util.Arrays; import java.util.Scanner; public class Maze { enum Direction{ UP, DOWN, RIGHT, LEFT; } public int[][] buidMaze( int n ){ int[][] maze = new int[n][n]; for( int[] a : maze ){ Arrays.fill(a, 0); } 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 ); } }