Java: 列印魔方陣__Java

來源:互聯網
上載者:User

輸入一個自然數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 ); } }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.