java如何给二维数组赋值使得每行每列都是递增的 5
展开全部
给你写了个比较通用的哈。。
public class MagicSquare {
/**
* @param args
*/
//注意只能产生奇数的魔术方阵 偶数的规律不一样
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] square = generateSquare(3);
for(int[] nums : square) {
for(int num : nums) {
System.out.printf("%-4d", num);
}
System.out.println();
}
}
//产生魔术方阵的方法 注意只能是奇数方阵哈 参数count就是你想要产生几阶的
public static int[][] generateSquare(int count) {
int[][] square = new int[count][count];
int row = 0;
int col = count / 2;
square[row][col] = 1;
for(int i = 2; i <= count * count; i++) {
row--;
col--;
if(row < 0) {
row = count - 1;
}
if(col < 0) {
col = count - 1;
}
if(square[row][col] != 0) {
if(row == count - 1) {
row = 0;
} else {
row++;
}
if(col == count - 1) {
col = 0;
} else {
col++;
}
row++;
if(row > count - 1) {
row = 0;
}
}
square[row][col] = i;
}
return square;
}
}
public class MagicSquare {
/**
* @param args
*/
//注意只能产生奇数的魔术方阵 偶数的规律不一样
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] square = generateSquare(3);
for(int[] nums : square) {
for(int num : nums) {
System.out.printf("%-4d", num);
}
System.out.println();
}
}
//产生魔术方阵的方法 注意只能是奇数方阵哈 参数count就是你想要产生几阶的
public static int[][] generateSquare(int count) {
int[][] square = new int[count][count];
int row = 0;
int col = count / 2;
square[row][col] = 1;
for(int i = 2; i <= count * count; i++) {
row--;
col--;
if(row < 0) {
row = count - 1;
}
if(col < 0) {
col = count - 1;
}
if(square[row][col] != 0) {
if(row == count - 1) {
row = 0;
} else {
row++;
}
if(col == count - 1) {
col = 0;
} else {
col++;
}
row++;
if(row > count - 1) {
row = 0;
}
}
square[row][col] = i;
}
return square;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询