Classical algorithm (21) Graduates will be eight queens problem [algorithm]

EDITORIAL : I am a "sail to the sea", the nickname comes from the name of my girlfriend's name as well. I love technology, open source love, love programming. 技术是开源的、知识是共享的.

This blog is a little summary and record their own learning, if you have the Java , algorithms interested, you can focus on my dynamic, we learn together.

用知识改变命运,让我们的家人过上更好的生活.

related articles

Click here to view algorithm [series] blog articles


1. Description of the problem

八皇后问题, An ancient and well-known problems, is a typical case of backtracking algorithms. The issues raised by the international chess player Max Bethel in 1848: 在 8×8 格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上asked how many pendulum method. Gauss think there are 76 kinds of programs. 1854 in Berlin on different chess magazine published 40 kinds of different solutions, then someone solve 92 kinds of results using graph theory. After the invention of the computer, there are a variety of computer programming languages may solve this problem.

I believe we have played 死亡八皇后游戏, here is what I play online games recorded screen.

Here Insert Picture Description

2, problem analysis

Objective : place eight queens on a chess 8 × 8 grid

Rules : Any two queens can not be in the same line, same column or the same diagonal

Since the queen can not be any peer, so that each row up to put a queen;
Since the number of rows equal to the number Queen, so that each row at least a queen.

Conclusion :每一行一定是放一个皇后

3, to achieve logic

Here Insert Picture Description

① First, a queen in the first line 1 8 × 8 grid of chess column 1

② Then put the second queen, trying to put the first column of the second row, and then determine whether the rule is satisfied. If not, continue to try in the second column, the third column position ... try to put all the columns of all finished, find a suitable placement.

③ continue to put a third queen, and placement process step ② empathy.

④ so on, put the fourth, fifth, sixth, seventh, eighth Queen

⑤ When to get a correct solution when:

The eighth attempt to move the placement of the Queen, to see if there is no other way place;
try to move the placement of the seventh Queen's see if there is no other way place;
try to move the placement of the sixth Queens, look there is no other way to put;
... ...
and so on, the fifth, fourth, third, second position to move the Queen to see if there is no other way to put.
This was the first Queen on the first row, first column all possibilities

⑥ then continues back to the first column of a second queen put behind the cycle continues performing the above step ①, ②, ③, ④, ⑤

To use in the process 回溯算法of thinking, 从一条路往前走,能进则进,不能进则退回来,换一条路再试。Eight Queens backtracking algorithms typical problem is the first step in order to put a queen, then the second step in line with the requirements put the first two queens, if there is no position to meet the requirements, then we must change first location of a queen, and re-released position of the two queens, until you find qualified position on it.

Back in the maze search problem using very common, this road is a dead end, then return to the previous intersection and continue down the road.

使用一个一维数组表示皇后的位置,其中数组的下标表示皇后所在的行,也就是第几个皇后,数组元素的值表示皇后所在的列。

4, code implementation

package com.study.algorithm;

/**
 * @Description:
 * @Author: 扬帆向海
 * @Date: Created in 01:26 2020/4/4
 */
public class EightQueens {

    static final int COUNT = 8;

    /**
     * 用一维数组存放皇后的摆放位置
     */
    static int[] array = new int[COUNT];
    /**
     * 用来记录有多少种摆放方案
     */
    static int sum = 0;

    public static void main(String[] args) {
        putQueen(0);
        System.out.println("八皇后总共有" + sum + "种摆放方案");
    }

    /**
     * 在棋盘上摆放皇后
     *
     * @param n 第几个皇后
     */
    public static void putQueen(int n) {
        // 如果n=COUNT,表示皇后放置完毕
        if (n == COUNT) {
            System.out.print((sum + 1) + "、八皇后的摆放位置是:");
            for (int i = 0; i < COUNT; i++) {
                int pos = array[i] + 1;
                System.out.print(pos + " ");
            }
            System.out.println();
            System.out.print("摆放位置如下图所示:");
            printPlace();
            return;
        } else {
            // 依次往棋盘中放入皇后
            for (int i = 0; i < COUNT; i++) {
                // 先把当前这个皇后n,放到该行的第一列
                array[n] = i;
                // 调用方法,判断把第n个皇后在第i列时,是否有冲突
                if (checkPlace(n)) {
                    // 不冲突,接着放置第(n+1)个皇后,即开始递归
                    putQueen(n + 1);
                }
            }
        }
    }

    /**
     * 绘制COUNT×COUNT棋盘,打印皇后的位置
     */
    public static void printPlace() {
        System.out.println();
        sum++;
        for (int i = 0; i < COUNT; i++) {
            System.out.print(" ");
            for (int j = 0; j < COUNT; j++) {
                System.out.print("---");
            }
            System.out.println();
            for (int k = 0; k < COUNT; k++) {
                if (k == array[i]) {
                    System.out.print("|" + "♛");
                } else {
                    System.out.print("| " + " ");
                }
            }
            System.out.println("|");
        }
        System.out.print(" ");
        for (int i = 0; i < COUNT; i++) {
            System.out.print("---");
        }
        System.out.println();
    }

    /**
     * 检查皇后的摆放位置是否有冲突
     *
     * @param n 表示第几个皇后
     * @return
     */
    public static boolean checkPlace(int n) {
        for (int i = 0; i < n; i++) {
            // 一维数组的值表示该行的列值,如果值相同,则表示在同一列
            // n-i表示两个皇后相差几行,array[n]-array[i]表示相差几列,如果相减的绝对值相等,则表示在对角线上
            if (array[i] == array[n] || Math.abs(n - i) == Math.abs(array[n] - array[i])) {
                return false;
            }
        }
        return true;
    }
}

Code execution results :

总共有 92 种摆放方案,由于篇幅有些,在此只截取了两种方案。

Here Insert Picture Description

Here Insert Picture Description


As limited, blog will inevitably be some mistakes, there is leakage of careless wing heavyweights at implore you!

Published 101 original articles · won praise 4287 · Views 790,000 +

Guess you like

Origin blog.csdn.net/weixin_43570367/article/details/104495769