把1-n*n个自然数填入n*n个格子中要求行,列,及对角线之和一致
import java.util.Scanner; public class AddModel { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n; System.out.println("Input n(add):"); n = in.nextInt(); while ((n & 1) != 1) { System.out.println("Input n(add):"); n = in.nextInt(); } int[][] mat = new int[n][n]; int r0 = 0, r1, r2, c0 = n / 2, c1, c2, cnt = 1; mat[r0][c0] = cnt; while (true) { if(cnt == n * n) break; r1 = r0 - 1; c1 = c0 +1; if(r1 < 0) r1 = n -1; if(c1 > n-1) c1 = 0; if (mat[r1][c1] == 0) { mat[r1][c1] = ++cnt;r0 = r1; c0 = c1; } else { r2 = r0+1; c2 = c0; if(r2 > n-1) r2 = 0; mat[r2][c2] = ++cnt; r0 = r2; c0 = c2; } } for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { System.out.print(mat[i][j] + "/t"); } System.out.println(); } } }
把n*n个数以逆时针的方式填入n*n个格子中
import java.util.*; public class AntiClockWise { public static void main (String[] args) { Scanner in = new Scanner(System.in); int[][] dir = new int[][]{{1,0},{0,1},{-1,0},{0,-1}}; System.out.println("Input n:"); int n = in.nextInt(); int[][] mat = new int[n][n]; int curr = 0, nextr = 0, curc = 0, nextc = 1, cnt = 1,type = 0; mat[0][0] = 1; while(true) { if(cnt == n*n) break; nextr = curr + dir[type][0]; nextc = curc + dir[type][1]; mat[nextr][nextc] = ++cnt; curr = nextr; curc = nextc; int next2r = curr + dir[type][0], next2c = curc + dir[type][1]; if( next2r < 0 || next2r >=n || next2c <0 || next2c >=n || mat[next2r][next2c] != 0) { type = (type+1) % 4; } } for(int i=0; i<n; ++i) { for(int j=0; j<n; ++j) { System.out.print(mat[i][j]+"/t"); } System.out.println(); } } }
83

被折叠的 条评论
为什么被折叠?



