Print the Rubik's Cube
Enter a natural number N (2≤N≤9), and require the following cube matrix to be output, that is, the side length is N*N, the elements are taken from 1 to N*N, and 1 is in the upper left corner, and each element is placed in a clockwise direction. When N=3:
1 2 3 8 9 4 7 6 5
[Input Form] Read an integer N from standard input.
[Output Form] Print the result to the standard output. The square matrix that meets the requirements is output, each number occupies 5 characters in width, is aligned to the right, and a carriage return character is output at the end of each line.
【Input Sample】 4
【Output Sample】
1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7
accomplish:
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 ); } }Print diamond graphics
The effect of the diamond picture is probably like this:
Let's look at the code below
package cn.dfeng; /** * This class can use * to print diamond graphic with ** @author dfeng * */ public class Drawer { /** * Print diamond graphic* @param n Diamond size*/ public void printDiamond( int n ){ System.out.println(); int i = 0; boolean flag = true; while( i >= 0 ){ if (i < n) { for (int j = 0; j < n - i; j++) { System.out.print(" "); } for (int j = n - i; j <= n + i; j += 2) { System.out.print("* "); } System.out.println(); } if (i == n) { flag = false; i--; } if (flag) { i++; } else { i--; } } } }