码迷,mamicode.com
首页 > 编程语言 > 详细

蛇形数组

时间:2016-04-05 12:15:25      阅读:139      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!