太难了,唯一Ac100%的题
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int n= in.nextInt(); int[][] arr=new int[n][n]; solution(n,arr); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } } } private static void solution(int n, int[][] arr) { if (n%2==0){ int left=0; int right =n-1; int top= 0; int bottom=n-1; int t=n-1; while (left<=right&&top <=bottom){ for (int i=right;i>=left; i--){ if (i==right||i==left){ arr[top][i]=0; continue; } if (i>(t)/2){ arr[top][i]=1; }else { arr[top][i]=2; } } top++; for (int i=top;i<=bottom; i++){ if (i==bottom){ arr[i][left]=0; continue; } if (i>(t)/2){ arr[i][left]=4; }else { arr[i][left]=3; } } left++; for (int i=left;i<=right; i++){ if (i==right){ arr[bottom][i]=0; continue; } if (i>(t)/2){ arr[bottom][i]=6; }else { arr[bottom][i]=5; } } bottom--; for (int i=bottom;i>=top; i--){ if (i>(t)/2){ arr[i][right]=7; }else { arr[i][right]=8; } } right--; } }else { int left=0; int right =n-1; int top= 0; int bottom=n-1; int t=n-1; while (left<=right&&top <=bottom){ for (int i=right;i>=left; i--){ if (i==right||i==left||i==t/2){ arr[top][i]=0; continue; } if (i>(t)/2){ arr[top][i]=1; }else { arr[top][i]=2; } } top++; for (int i=top;i<=bottom; i++){ if (i==bottom||i==t/2){ arr[i][left]=0; continue; } if (i>(t)/2){ arr[i][left]=4; }else { arr[i][left]=3; } } left++; for (int i=left;i<=right; i++){ if (i==right||i==t/2){ arr[bottom][i]=0; continue; } if (i>(t)/2){ arr[bottom][i]=6; }else { arr[bottom][i]=5; } } bottom--; for (int i=bottom;i>=top; i--){ if (i==t/2){ arr[i][right]=0; continue; } if (i>(t)/2){ arr[i][right]=7; }else { arr[i][right]=8; } } right--; } } } }
全部评论
(2) 回帖