DLX Algorithm number single game Java version __ Code

Source: Internet
Author: User
Tags int size
Use DLX algorithm to number single game.
Beginners Java, the algorithm code is converted by C code.
Dlx.java is an algorithm class, Sudoku.java is an interface class.
The solution is known as the most difficult sudoku in the world within 10ms.


algorithm Detailed

Sudoku Dancing Links Template use method int n = 9;
DLX DLX = new DLX (n * n * n + 1, 4 * n * n);
Dlx.setnum (5)//Up to 5 solutions, default 2
Dlx.solve (data);//int data[9][9];

List<int[][]> solutions = dlx.getsolutions ();


code Download

Https://code.google.com/p/sudoku-dlx/source/checkout

Dlx.java

Import java.util.ArrayList;

Import java.util.List;
	public class DLX {private static final int ROW = 4096 + 50;
	private static final int COL = 1024 + 50;
	private static final int N = 4 * 9 * 9;

	private static final int m = 3;
	Dlxnode row[] = new Dlxnode[row];
	Dlxnode col[] = new Dlxnode[col];

	Dlxnode Head;
	private int n;
	private int num = 2;
	private int size[] = new Int[col];
	int data[][] = new INT[9][9];

	List<int[][]> Solutions;
		Public DLX (int r, int c) {n = m * m;
		Head = new Dlxnode (r, c); Head. U = head. D = head. L = head.
		R = head;
			for (int i = 0; i < C; ++i) {Col[i] = new Dlxnode (r, I); Col[i].
			L = head; Col[i]. R = head.
			R Col[i]. L.R = Col[i].
			R.L = Col[i]; Col[i]. U = Col[i].
			D = Col[i];
		Size[i] = 0;
			for (int i = r-1 i >-1; i.) {row[i] = new Dlxnode (i, c); Row[i].
			U = head; Row[i]. D = head.
			D Row[i]. U.D = Row[i].
			D.U = Row[i]; Row[i]. L = Row[i].
		R = Row[i];
	}} public void AddNode (int r, int c){Dlxnode p = new Dlxnode (r, c);
		P.R = Row[r]; P.L = Row[r].
		L
		P.L.R = P.R.L = P;
		P.U = Col[c]; P.D = Col[c].
		D
		P.U.D = P.D.U = P;
	++SIZE[C];
		The public void AddNode (int i, int j, int k) {int r = (I * n + j) * n + k;
		AddNode (R, I * n + k-1);
		AddNode (r, N * n + + J * n + k-1);
		AddNode (r, 2 * N * n + block (i, j) * n + k-1);
	AddNode (r, 3 * n * n + i * n + j);
	int block (int x, int y) {return x/m * m + y/m;

		public void cover (int c) {if (c = N) return;
		Col[c].dellr ();
		Dlxnode R, C; for (C = Col[c]. D C!= Col[c];
			C = c.d) {if (C.C = N) continue; for (R = C.L; R!= C;
				R = R.L) {if (r.c = = N) continue;
				--SIZE[R.C];
			R.delud ();
		} C.DELLR ();

		} public void resume (int c) {if (c = N) return;
		Dlxnode R, C; for (C = Col[c]. U C!= Col[c];
			C = c.u) {if (C.C = N) continue;
			C.RESUMELR (); for (R = C.R; R!= C;
				R = R.R) {if (r.c = = N) continue; ++sIZE[R.C];
			R.resumeud ();
	} COL[C].RESUMELR (); public boolean solve (int depth) {if head.
			L = = head) {int solution[][] = new Int[n][n];
			for (int i = 0; i < n; ++i) for (int j = 0; J < N; ++j) solution[i][j] = Data[i][j];

			Solutions.add (solution);
			if (solutions.size () = num) return true;
		return false;
		int minsize = 1 << 30;
		int c =-1;
		Dlxnode p; for (P = head. L P!= Head;
				p = p.l) if (Size[p.c] < minsize) {minsize = size[p.c];
			c = p.c;

		} cover (c); for (P = col[c]. D P!= Col[c];
			p = p.d) {Dlxnode cell;
			P.R.L = p; for (cell = P.L cell!= p; cell = cell.)
			L) {cover (CELL.C);
			} P.R.L = P.L;
			int rr = p.r-1;
			DATA[RR/(n * N)][rr/n% n] = RR% n + 1;

			if (Solve (depth + 1)) return true;
			P.L.R = p; for (cell = P.R cell!= p; cell = cell.)
			R) resume (CELL.C);
		P.L.R = P.R;
		} resume (c);
	return false; public boolean solve (int data[][]) {init (data);
	return solve (0);
		public void init (int data[][]) {solutions = new arraylist<int[][]> ();
		int I, j, K; for (i = 0; i < n; ++i) for (j = 0; J < N; ++j) {if (data[i][j) > 0) {addNode (I, J, data[i][
				J]);
				else {for (k = 1; k <= N; ++k) AddNode (i, J, K);
	}} public void setnum (int num) {this.num = num;
	public int Getnum () {return num;
	Public list<int[][]> getsolutions () {return solutions;
	} class Dlxnode {int r,c;
	
	Dlxnode U,d,l,r;
	Dlxnode () {r = c = 0;
		} dlxnode (int r, int c) {THIS.R = R;
	THIS.C = C;
		Dlxnode (int r, int c, Dlxnode U, Dlxnode D, Dlxnode L, Dlxnode r) {THIS.R = R;
		THIS.C = C; This.
		u = u; This.
		D = D; This.
		L = l; This.
	R = r;
		public void Dellr () {L.R = R;
	R.L = L;
		public void Delud () {u.d = D;
	d.u = U;
	public void Resumelr () {L.R = R.L = this;
public void Resumeud () {		U.D = D.U = this; }
}

Sudoku.java

Import java.awt.*;

Import java.awt.event.*;
Import javax.swing.*;
Import Javax.swing.border.LineBorder;
Import Javax.swing.border.TitledBorder;
Import Javax.swing.plaf.basic.BasicArrowButton;

Import javax.swing.text.*;
	public class Sudoku extends JPanel {/** * */private static final long serialversionuid = 1L;
	private static final int width = 9;
	private static final int height = 9;
	private int data[][] = new Int[height][width];

	Private String infostr = "";
	JButton solve = new JButton ("Solve"), reset = new JButton ("reset"), clean = new JButton ("clean"); Basicarrowbutton right = new Basicarrowbutton (basicarrowbutton.east), left = new Basicarrowbutton (
	Basicarrowbutton.west);
	JTextField sudokus[][] = new Jtextfield[height][width];

	Jtextpane info = new Jtextpane ();
	Java.util.list<int[][]> Solutions;

	private int solutionidx = 0;
		Sudoku () {setlayout (null); for (int r = 0; r < 3, ++r) {for (int c = 0; c < 3; ++c) {JPanel JP = new JPanel ();
				Jp.setlayout (NULL);
				Jp.setbounds (R * + 5, c * 95 + 5, 95, 95);
				
				Jp.setborder (New Lineborder (Color.Black));
						for (int x = 0; x < 3; ++x) for (int y = 0; y < 3; ++y) {int J = R * 3 + x, i = c * 3 + y;
						SUDOKUS[I][J] = new JTextField ();
						Sudokus[i][j].setbounds (x + 5, Y + 5, 25, 25);
						Sudokus[i][j].setdocument (New NUMBERLENGHTLIMITEDDMT (1));
					Jp.add (Sudokus[i][j]);
			Add (JP);
		} solve.setbounds (85, 300, 75, 25);
		Solve.addactionlistener (New Solveal ());

		Add (solve);
		Reset.setbounds (175, 300, 75, 25);
		Reset.addactionlistener (New Resetal ());

		Add (reset);
		Clean.setbounds (265, 300, 75, 25);
		Clean.addactionlistener (New cleanal ());

		Add (clean);
		Left.setvisible (FALSE);
		Left.setbounds (170, 330, 50, 25);
		Left.addactionlistener (New PrevAL ());
		
		Add (left);
		Right.setvisible (FALSE);
		Right.setbounds (230, 330, 50, 25);
		Right.addactionlistener (New Nextal ());

		Add (right); JscrolLpane jsp = new JScrollPane (info);
		Info.seteditable (FALSE);
		Jsp.setbounds (300, 5, 140, 285);
		Jsp.setborder ("Info") (new Titledborder);
	Add (JSP);
		public boolean Solve () {int i, J; for (i = 0; i < height; ++i) {for (j = 0; J < width; ++j) {try {data[i][j] = Integer.parsein
					T (Sudokus[i][j].gettext ());
				Sudokus[i][j].seteditable (FALSE);
					catch (NumberFormatException e) {data[i][j] = 0;
				Sudokus[i][j].setenabled (FALSE);
		{}} int n = 9;
		Long starttime = System.currenttimemillis ();
		DLX DLX = new DLX (n * n * n + 1, 4 * n * n);
		Dlx.setnum (5);
		Dlx.solve (data);

		Solutions = Dlx.getsolutions ();
		if (Solutions.size () > 1) infostr + = "Find multi solutions.\n";
		else if (solutions.size () > 0) Infostr + = "Find one solution.\n";
		else Infostr + = "Cannot find a solution.\n";

		Infostr + = "Used Time:" + (System.currenttimemillis ()-StartTime) + "ms\n";
	return update (); public void ResET (int data[][]) {solve.setenabled (true);
		int I, J;
				for (i = 0; i < height; ++i) {for (j = 0; J < width; ++j) {sudokus[i][j].setenabled (true);
				Sudokus[i][j].seteditable (TRUE);
				if (data[i][j] = = 0) {sudokus[i][j].settext ("");
				else {sudokus[i][j].settext (integer.tostring (Data[i][j]));
		}}} Boolean update () {info.settext (INFOSTR);

		if (Solutionidx >= solutions.size ()) return false;
		Left.setvisible (TRUE);
		Right.setvisible (TRUE);
		int I, J;
		int solution[][] = Solutions.get (SOLUTIONIDX); for (i = 0; i < height; ++i) {for (j = 0; J < width; ++j) {Sudokus[i][j].settext (integer.tostring Solu
			TION[I][J]));
	} return true;
		public static void Inframe (JPanel jp, int width, int height) {String title = "Sudoku";
		JFrame frame = new JFrame (title);
			Frame.addwindowlistener (New Windowadapter () {public void windowclosing (WindowEvent e) {system.exit (0);
	}	});
		Frame.getcontentpane (). Add (JP, borderlayout.center);
		Frame.setlocationbyplatform (TRUE);
		Frame.setsize (width, height);
		Frame.setresizable (FALSE);
	Frame.setvisible (TRUE);  public static void Main (string[] args) {int data[][] = {{8, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 3, 6, 0,  
				0, 0, 0, 0}, {0, 7, 0, 0, 9, 0, 2, 0, 0}, {0, 5, 0, 0, 0, 7, 0, 0, 0}, {0, 0, 0, 0, 4, 5, 7, 0, 0}, {0, 0, 0, 1, 0, 0, 0, 3, 0}, {0, 0, 1, 0, 0, 0, 0, 6, 8}, {0, 0, 8, 5, 0, 0, 0, 1, 0}, {0 and 9
		, 0, 0, 0, 0, 4, 0, 0},};
		Sudoku Sudoku = new Sudoku ();
		Sudoku.reset (data);
	Inframe (Sudoku, 450, 400);  Class Solveal implements ActionListener {public void actionperformed (ActionEvent e) {infostr = "Start Solve
			This sudoku.\n ";
			Info.settext (INFOSTR);
			Solve.setenabled (FALSE);
		Solve (); } class Resetal implements ActionListener {public void actionperformed (ActionEvent e) {infostr = "Reset su DokU data.\n ";
			Info.settext (INFOSTR);
			Left.setvisible (FALSE);
			Right.setvisible (FALSE);
		Reset (data); } class Cleanal implements ActionListener {public void actionperformed (ActionEvent e) {infostr = ' clean Sud
			Oku data.\n ";
			Info.settext (INFOSTR);
			Solve.setenabled (TRUE);
			Left.setvisible (FALSE);
			Right.setvisible (FALSE);
			int I, J;
					for (i = 0; i < height; ++i) {for (j = 0; J < width; ++j) {Sudokus[i][j].settext ("");
					Sudokus[i][j].setenabled (TRUE);
				Sudokus[i][j].seteditable (TRUE); Class PrevAL implements ActionListener {public void actionperformed (ActionEvent e) {int size =
			Solutions.size ();
				if (Size > 0) {solutionidx = (solutionIdx-1 + size)% size;
				Infostr + = "the" + (solutionidx+1) + "th solution.\n";
			Update (); Class Nextal implements ActionListener {public void actionperformed (ActionEvent e) {int size = Soluti
			Ons.size (); if (size;
				0) {Solutionidx = (solutionidx + 1)% size;
				Infostr + = "the" + (solutionidx+1) + "th solution.\n";
			Update (); }} class Numberlenghtlimiteddmt extends Plaindocument {/** * */private static final long Serialversi
		Onuid = 1L;

		private int limit;
			public numberlenghtlimiteddmt (int limit) {super ();
		This.limit = limit; public void insertstring (int offset, String str, AttributeSet attr) throws badlocationexception {if (str = = nul
			L) {return;
				} if ((GetLength () + str.length ()) <= limit) {char[] upper = Str.tochararray ();
				int length = 0; for (int i = 0; i < upper.length i++) {if (Upper[i] >= ' 0 ' && upper[i] <= ' 9 ') {Up
					per[length++] = Upper[i];
			} super.insertstring (offset, new String (upper, 0, length), attr); }
		}
	}

}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.