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

打印蛇形矩阵的java实现

时间:2014-11-02 00:45:49      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:java 方阵填数

smartOJ[NOIP1995P3]


import java.util.*;


public class Main 

{

public static void main(String[] args) {

String str =null;

Scanner scanner = new Scanner(System.in);

int n = scanner.nextInt();

int[][] numbers = new int[n][n];

boolean[][] isE = new boolean[n][n];

int x=0,y=n-1,k=1;

numbers[x][y]=k++;

isE[x][y] = true;

while(k<= n*n){

while(x<n-1 && !isE[x+1][y]){

x++;

numbers[x][y]=k++;

isE[x][y] = true;

}

while(y>0 && !isE[x][y-1]){

y--;

numbers[x][y]=k++;

isE[x][y] = true;

}

while(x>0 && !isE[x-1][y]){

x--;

numbers[x][y]=k++;

isE[x][y] = true;

}

while(y<n-1 && !isE[x][y+1]){

y++;

numbers[x][y]=k++;

isE[x][y] = true;

}

}

//格式输出

if(n<4){

for(int i=0;i<n;i++){

for(int j=0; j<n; j++){

System.out.printf("%d ",numbers[i][j]);

}

System.out.println();

}

} else if(n<10){

for(int i=0;i<n;i++){

for(int j=0; j<n; j++){

System.out.printf("%2d ",numbers[i][j]);

}

System.out.println();

}

} else if(n==10){

for(int i=0;i<n;i++){

for(int j=0; j<n; j++){

System.out.printf("%3d ",numbers[i][j]);

}

System.out.println();

}

}

}

}


本文出自 “8132191” 博客,请务必保留此出处http://8142191.blog.51cto.com/8132191/1570777

打印蛇形矩阵的java实现

标签:java 方阵填数

原文地址:http://8142191.blog.51cto.com/8132191/1570777

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!