本题要求将给定的N个正整数按非递增的顺序,填入“螺旋矩阵”。所谓“螺旋矩阵”,是指从左上角第1个格子开始,按顺时针螺旋方向填充。要求矩阵的规模为m行n列,满足条件:m*n等于N;m>=n;且m-n取所有可能值中的最小值。
输入格式:
输入在第1行中给出一个正整数N,第2行给出N个待填充的正整数。所有数字不超过104,相邻数字以空格分隔。
输出格式:
输出螺旋矩阵。每行n个数字,共m行。相邻数字以1个空格分隔,行末不得有多余空格。
输入样例:12 37 76 20 98 76 42 53 95 60 81 58 93输出样例:
98 95 93 42 37 8153 20 76
import java.util.*; public class Main { static Scanner in=new Scanner(System.in); static Comparator<Integer> com =new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2-o1; } }; public static void main(String[] args) { while(in.hasNext()){ int k=in.nextInt(); Integer[] a=new Integer[k]; int n,m; for (int i = 0; i <k; i++) a[i]=in.nextInt(); Arrays.sort(a, com); n =(int) Math.sqrt(k); m=k/n; while(m*n!=k){ n--; m=k/n; } int[][] r=new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { r[i][j]=-1; } } int x=0,y=0,cnt=0; r[x][y]=a[cnt++]; while(cnt<m*n){ while(y+1<n&&r[x][y+1]==-1) {r[x][++y]=a[cnt++];} while(x+1<m&&r[x+1][y]==-1) {r[++x][y]=a[cnt++];} while(y-1>=0&&r[x][y-1]==-1) {r[x][--y]=a[cnt++];} while(x-1>=0&&r[x-1][y]==-1) {r[--x][y]=a[cnt++];} } for (int i = 0; i <m; i++) { for (int j = 0; j <n; j++) { System.out.print(r[i][j]); if(j!=n-1) System.out.print(" "); } System.out.println(); } } } }
注意求解m和n的方法,有两个点超时,头疼!