要有代码实现!
将字符串:123456789 填入3x3的矩形中,使其横竖斜相加和等于15
- 提问者网友:浮克旳回音
- 2021-05-17 08:50
- 五星知识达人网友:冷風如刀
- 2021-05-17 10:04
public static int[][] matrix = new int[3][3];
public static boolean[] flag = new boolean[9];
public static void init() {
int i;
for (i = 0; i < 9; i++) {
flag[i] = false;
}
}
public static void calculateMatrix(int step) {
if (9 == step) {
int j;
for (j = 0; j < 3; j++) {
int sum = 0;
int k;
for (k = 0; k < 3; k++) {
sum += matrix[j][k];
}
if (15 != sum) {
return;
}
}
for (j = 0; j < 3; j++) {
int sum = 0;
int k;
for (k = 0; k < 3; k++) {
sum += matrix[k][j];
}
if (15 != sum) {
return;
}
}
if (15 != matrix[0][0] + matrix[1][1] + matrix[2][2]) {
return;
}
if (15 != matrix[0][2] + matrix[1][1] + matrix[2][0]) {
return;
}
for (j = 0; j < 3; j++) {
int k;
for (k = 0; k < 2; k++) {
System.out.print(matrix[j][k]);
System.out.print(" ");
}
System.out.println(matrix[j][2]);
}
System.out.println();
System.out.println();
}
int i;
for (i = 0; i < 9; i++) {
if (!flag[i]) {
flag[i] = true;
matrix[step / 3][step % 3] = i + 1;
calculateMatrix(step + 1);
flag[i] = false;
}
}
}
public static void main(String[] args) {
init();
calculateMatrix(0);
}
- 1楼网友:行路难
- 2021-05-17 11:45
main()
{
int mf[3][3];
int i=0;
int j=1;
int s=1;
while(s<10)
{
mf[i][j]=s;
--i;
if(i<0)i=2;
++j;
if(j>2)j=0;
++s;
}
for(i=0;i<3;i++)
{
for(j=0;j<3,j++)
printf(" %d",mf[i][j]);
printf("\n");
}
}
- 2楼网友:渡鹤影
- 2021-05-17 11:27