Put eight queens on the 8x8 chess, so that they can not attack each other, that is, any two queens can not be in the same row, the same column or the same slash, ask how many kinds of pendulum.
(text and pictures from Baidu Encyclopedia)
If you put the Queen, you can use a way of thinking: Drop a Queen in the leftmost column, and then in the right column from top to bottom to find the first place with the left Queen does not conflict with the second Queen, and then to yo one column, from top to bottom to find the first two queen in the position of the third Queen, and so on, Until the eighth Queen is placed in the last column.
Serious thinking, you can find that this is still the depth of the first search idea, that is, stepping forward, the next thing to do is the same as at present. Code:
[Java]View PlainCopyprint?
- Public class Dfseightqueens {
- int[] Queens = new int[8]; //Record the position of the Queen in each column
- int count = 0; //Pendulum total
- public void Dfs (int column) {
- if (column = = 8) { //8 queens have been placed
- count++;
- System.out.println ("n" + Count + "method:");
- Print ();
- return;
- }
- For (int i = 0; i < 8; i++) {
- Queens[column] = i; //Place the Queen on line I of the column
- if (isValid (column)) //Check whether the position is in conflict with the Queen of the former column-1 column
- DFS (column + 1); //No conflict start the next 8-position attempt
- }
- }
- Private Boolean isValid (int column) {
- for (int i = 0; i < column; i++) { ///column above the Queen compared to the front column-1 Queen
- if (queens[i] = = Queens[column]) //Two queens on the same line
- return false;
- if (Math.Abs (Queens[i]-queens[column]) = = (column-i)) //Two queens on the same diagonal
- return false;
- }
- return true;
- }
- private void print () {
- For (int i = 0; i < 8; i++) {
- For (int j = 0; j < 8; j + +) {
- if (queens[i] = = j)
- System.out.print ("*");
- Else
- System.out.print ("_");
- }
- System.out.println ();
- }
- }
- public static void Main (string[] args) {
- Dfseightqueens q = new Dfseightqueens ();
- Q.dfs (0);
- System.out.println ("Total" + Q.count + "method of placement");
- }
- }
Output:
[Java]View PlainCopyprint?
- A total of 92 kinds of placement methods
Java and Algorithm (6)-eight Queen's question