Java: Print the magic square __java

Source: Internet
Author: User

Enter a natural number N (2≤n≤9), which requires the output of the following magic square, that is, the edge length is n*n, the element value is 1 to n*n,1 in the upper left corner, in turn the elements in a clockwise direction. When   n=3:
     1    2    3    
     8    9    4    &NBSP
     7    6    5 
Input form "  reads an integer n from the standard input.   
Output form   Print results to standard output. The output matches the required phalanx, each number is 5 characters wide, aligned to the right, and a carriage return is output at the end of each line. &NBSP
"Input sample"   4
"Output sample"      
    1     2    3    4  
   12    13   14    5 
   11   16    15    6   
   10     9    8    7

Realize:

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 &&amp ; 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); } }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.