// NQueenClient // // import java.awt.Graphics; class NQueen { protected int n; protected int board[]; protected boolean rows[], up[], down[]; protected NQueenApplet ap; NQueen(NQueenApplet ap) { this.ap = ap; n = ap.getN(); rows = new boolean[n]; board = new int[n]; up = new boolean[2 * n - 1]; down = new boolean[2 * n - 1]; for (int i = 0; i < n; i++) { board[i] = 0; rows[i] = true; } for (int i = 2 * n - 2; i >= 0; i--) { up[i] = true; down[i] = true; } } public int[] getBoard() { return board; } public void try_it(int col) { for (int row = 0; row < n; row++) { if (rows[row] && up[col + row] && down[col - row + n - 1]) { board[col] = row; rows[row] = false; up[col + row] = false; down[col - row + n - 1] = false; if (col + 1 == n) ap.printIt(); else try_it(col + 1); rows[row] = true; up[col + row] = true; down[col - row + n - 1] = true; } } } } public class NQueenApplet extends java.applet.Applet implements Runnable { NQueen nq; Thread runner; int buffer[]; int c = 0; int n = 0; public int getN() { return n; } public void init() { n = 8; resize(300, 300); } public void start() { if (runner == null) { runner = new Thread(this); runner.start(); } } public void stop() { if (runner != null) { runner.stop(); runner = null; } } public void paint(Graphics g) { int x0 = 10; int y0 = 40; int dx = 20; int dy = 20; if (buffer == null) return; g.drawString("Count: " + c, x0, y0 - 15); for (int i = 0; i <= n; i++) { g.drawLine(x0, y0 + dy * i, x0 + dx * n, y0 + dy * i); g.drawLine(x0 + dx * i, y0, x0 + dx * i, y0 + dy * n); } for (int i = 0; i < n; i++) { g.drawString("Q", x0 + dx * i + 5, y0 + dy * (buffer[i] + 1) - 5); } } public void printIt() { buffer = nq.getBoard(); c++; repaint(); try { Thread.sleep(200); } catch (InterruptedException ie) {} } public void run() { c = 0; showStatus("nクイーン開始"); nq = new NQueen(this); nq.try_it(0); } }