U E D R , A S I H C RSS

Magic Square/인수

~cpp 
public class MagicSquare {
	int _size;
	int _x, _y;
	int _board[][];
	
	public MagicSquare(int size) {
		_size = size;
		_board = new int[_size][_size];
		for(int i = 0 ; i < _size ; ++i)
			for(int j = 0 ; j < _size ; ++j)
				_board[i][j] = 0;
		_x = _size/2;
		_y = 0;
	}
	void calcNextCoord() {
		int oldX = _x;
		int oldY = _y;		
		_x = setValidCoord(++_x);
		_y = setValidCoord(--_y);
		
		if(_board[_y][_x] != 0)	{
			_x = oldX;
			_y = oldY;
			++_y;
		}							
	}
	int setValidCoord(int c) {
		if(c == -1)
			c = _size - 1;
		else if(c == _size)
			c = 0;	
		return c;
	}
	void traverseSquare() {
		for(int i = 1 ; i <= _size*_size ; ++i) {
			_board[_y][_x] = i;
			calcNextCoord();
		}
	}
	void showBoard() {
		for(int i = 0 ; i < _size ; ++i) {
			for(int j = 0 ; j < _size ; ++j)
				System.out.print( _board[i][j] + " ");
			System.out.println(" ");
		}
	}
	public static void main(String args[]) {
		MagicSquare ms = new MagicSquare(5);
		ms.traverseSquare();
		ms.showBoard();
	}
}
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:23:43
Processing time 0.0095 sec