首页 > 编程语言 > 详细

蛇形数组

时间:2016-04-05 12:13:15      阅读:332      评论:0      收藏:0      [点我收藏+]

 

输入:4

输出:

1  2  3  4
12 13 14 5
11 16 15 6
10  9  8  7

 1 import java.util.Scanner;  
 2 
 3 public class SnakeString {  
 4     public static void main(String[] args){  
 5         Scanner sc = new Scanner(System.in);  
 6         System.out.println("please input the number:");  
 7         int number = sc.nextInt();  
 8         int x = 0;
 9         int y = 0;
10         int[][] numberMatric = new int[number][number];  
11         int num = 1;  
12         while(num <= number*number){  
13             while(y<number && numberMatric[x][y] == 0){
14                 numberMatric[x][y++] = num++;
15             }
16             y--;
17             x++;
18             while(x<number && numberMatric[x][y] == 0)
19                 numberMatric[x++][y] = num++;
20             y--;
21             x--;
22             while(y>=0 && numberMatric[x][y] == 0)
23                 numberMatric[x][y--] = num++;
24             y++;
25             x--;
26             while(x>=0 && numberMatric[x][y] == 0)
27                 numberMatric[x--][y] = num++;
28             y++;
29             x++;
30         }
31         
32         for(x = 0;x < number;x++){  
33             for(y = 0;y < number;y++){  
34                 System.out.printf("%4d",numberMatric[x][y]);  
35             }  
36             System.out.println();  
37         }  
38     }  
39 }  

 

蛇形数组

原文:http://www.cnblogs.com/shake-rock/p/5354472.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!