幻方的生成(java实现)

来自MIT的Magic Squares

http://web.mit.edu/6.031/www/fa19/

A magic square of order n is an arrangement of n×n numbers, usually distinct integers, in a square, such that the n numbers in all rows, all columns, and both diagonals sum to the same constant (see Wikipedia: Magic Square).
幻方是每行上的整数的和、每列上的整数的和以及两条对角线中的每条对角线上的整数的和都等于同一个数的n*n的方阵。

MIT提供的 generateMagicSquare函数采用的是delaloubere在17世纪发现的一种构造 n 阶幻方的方法,其中 n 是奇数。
代码如下:

public static boolean generateMagicSquare(int n){

		int magic[][] = new int[n][n];
		int row = 0, col = n / 2, i, j, square = n * n;// 初始化

		for (i = 1; i <= square; i++) {
			magic[row][col] = i;// 将1放在最上行的中间
			if (i % n == 0)
				row++;
			else {
				if (row == 0)
					row = n - 1;// 行数为第一行,将数放在底行
				else
					row--;// 行数减小
				if (col == (n - 1))
					col = 0;// 列数为最右列,放在最左列
				else
					col++;// 列数增加
			}
		}

		for (i = 0; i < n; i++) {
			for (j = 0; j < n; j++)
				System.out.write(magic[i][j] + "\t");
			System.out.println(); 
		}
		return true;
	}

梳理逻辑如下:
先将1放在第一行中间,然后自左下到右上的主对角线按自然顺序填数。到顶行时,下一个整数放在底行。到最后一列时,下一个整数放在最左边一列。想填的位置已经存在数,或者上一个整数放在矩阵右上角,将当前数填写在上个位置下方。n如果是偶数,左下角的元素会越界,即ArrayIndexOutOfBoundsException。n如果是负数,无法生成矩阵,即NegativeArraySizeException。


版权声明:本文为weixin_43864571原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。