描述:输入一个数字N(N>0)输出如下结果:
例如:N=3
1 2 3
8 9 4
7 6 5
法一:
package com.dmir.test; import java.util.Scanner; import java.util.logging.Logger; /** * Created by $wally on 2016/8/30. */ public class Main { public static void main(String[] args) throws Exception{ Scanner cin=new Scanner(System.in); int n =cin.nextInt(); int [][]array=new int[n][n]; int x=0,y=0;//起始点 int cnt=1; int lx=0,hx=n-1,ly=0,hy=n-1;//初始化边界 int N=n*n; while(cnt<=N){ while((y<=hy)&&(cnt<=N)){array[x][y]=cnt++;y++;} if(cnt>N) break; y--;x++;lx++; while((x<=hx)&&(cnt<=N)){array[x][y]=cnt++;x++;} if(cnt>N) break; x--;y--;hy--; while((y>=ly)&&(cnt<=N)){array[x][y]=cnt++;y--;} if(cnt>N) break; y++;x--;hx--; while((x>=lx)&&(cnt<=N)){array[x][y]=cnt++;x--;} if(cnt>N) break; x++;y++;ly++; } for(int i=0;i<n;++i){ for(int j=0;j<n;++j){ System.out.print(array[i][j] + " "); } System.out.println(); } } }
法二:
package com.dmir.test; import java.util.Scanner; /** * Created by $wally on 2016/8/30. */ public class Test { public static void main(String[] args) throws Exception{ Scanner cin=new Scanner(System.in); int n =cin.nextInt(); System.out.println(n); int [][]array=new int[n][n]; for(int i=0;i<n;++i){ for(int j=0;j<n;++j){ array[i][j]=0; } } int x=0,y=0;//起始点 int cnt=2; int N=n*n; array[x][y]=1; while(cnt<=N){ while((y+1<n)&&(array[x][y+1]==0)){array[x][++y]=cnt++;} while((x+1<n)&&(array[x+1][y]==0)){array[++x][y]=cnt++;} while((y-1>=0)&&(array[x][y-1]==0)){array[x][--y]=cnt++;} while((x-1>=0)&&(array[x-1][y]==0)){array[--x][y]=cnt++;} } for(int i=0;i<n;++i){ for(int j=0;j<n;++j){ System.out.print(array[i][j] + " "); } System.out.println(); } } }