蛇形矩阵-Java代码示例
import java.util.Scanner;
public class SeXingJuZhen {
public static void main(String[] args) {
Scanner reader=new Scanner(System.in);
int x=reader.nextInt();
int[][] a=new int[x][x];
int direction=1;//1,2,3,4分别表示右下左上
int i=0,j=0;
int index=1;
while(a[i][j]==0){
//对数组赋值
a[i][j]=index++;
//调整方向
direction=adjust(a,x,i,j,direction);
//判断下一步是横向移动还是纵向
if(direction==1){
j++;
}
if(direction==2){
i++;
}
if(direction==3){
j--;
}
if(direction==4){
i--;
}
}//while
for(i=0;i<x;i++){
for(j=0;j<x;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
public static int adjust(int[][] a,int x,int i,int j,int direction){
if(direction==1){
if(j==x-1){//到达边界
direction++;
}
else{
if(a[i][j+1]!=0){//下一个数已被修改
direction++;
}
}
}
if(direction==2){
if(i==x-1){//到达边界
direction++;
}
else{
if(a[i+1][j]!=0){//下一个数已被修改
direction++;
}
}
}
if(direction==3){
if(j==0){//到达边界
direction++;
}
else{
if(a[i][j-1]!=0){//下一个数已被修改
direction++;
}
}
}
if(direction==4){
if(i==0){//到达边界
direction=1;
}
else{
if(a[i-1][j]!=0){//下一个数已被修改
direction=1;
}
}
}
return direction;
}
}