如何编写一个SQL查询来解决8个皇后区的问题?

时间:2019-05-18 20:06:40

标签: mysql sql algorithm mysqli

表为:

+-------------+------------+------+-----+---------+----------------+
| Field       | Type       | Null | Key | Default | Extra          |
+-------------+------------+------+-----+---------+----------------+
| A           | VARCHAR(5)) | YES  |     | NULL    |                |
| B           | VARCHAR(5)  | YES  |     | NULL    |                |
| C           | VARCHAR(5)  | YES  |     | NULL    |                |
| D           | VARCHAR(5)  | YES  |     | NULL    |                |
| E           | VARCHAR(5)  | YES  |     | NULL    |                |
| F           | VARCHAR(5)  | YES  |     | NULL    |                |
| G           | VARCHAR(5)  | YES  |     | NULL    |                |
| H           | VARCHAR(5)  | YES  |     | NULL    |                |
+-------------+------------+------+-----+---------+----------------+

带有值

   A  B  C  D  E  F  G  H 
   A1 B1 C1 D1 E1 F1 G1 H1
   A2 B2 C2 D2 E2 F2 G2 H2
   A3 B3 C3 D3 E3 F3 G3 H3
   A4 B4 C4 D4 E4 F4 G4 H4
   A5 B5 C5 D5 E5 F5 G5 H5
   A6 B6 C6 D6 E6 F6 G6 H6
   A7 B7 C7 D7 E7 F7 G7 H7
   A8 B8 C8 D8 E8 F8 G8 H8

如何在MySQL中编写查询以解决8个皇后区的问题? 查询的形式应为以下形式的输出:

  A   B    C    D    E    F    G    H
 ---  ---  ---  ---  ---  ---  ---  --- 
 a7   b4   c2   d8   e6   f1   g3   h5

1 个答案:

答案 0 :(得分:1)

以4个皇后开始

-- data setup
create table tt(
X int,
Y int
)

insert tt(X,Y)
with n8(N) as (
    select 1 N
    union all 
    select 2
    union all
    select 3
    union all
    select 4
)
select t1.N,t2.N
from n8 t1, n8 t2

-- find solutions

select t1.X, t1.Y, t2.X, t2.Y , t3.X, t3.Y, t4.X, t4.Y --, t5.X, t5.Y, t6.X, t6.Y, t7.X, t7.Y, t8.X, t8.Y 
from tt t1
join tt t2 on t1.X <> t2.X and t1.Y <> t2.Y and abs (t1.X - t2.X) <> abs (t1.Y - t2.Y)
join tt t3 on t1.X <> t3.X and t1.Y <> t3.Y and abs (t1.X - t3.X) <> abs (t1.Y - t3.Y)
          and t2.X <> t3.X and t2.Y <> t3.Y and abs (t2.X - t3.X) <> abs (t2.Y - t3.Y)
join tt t4 on t1.X <> t4.X and t1.Y <> t4.Y and abs (t1.X - t4.X) <> abs (t1.Y - t4.Y)
          and t2.X <> t4.X and t2.Y <> t4.Y and abs (t2.X - t4.X) <> abs (t2.Y - t4.Y)
          and t3.X <> t4.X and t3.Y <> t4.Y and abs (t3.X - t4.X) <> abs (t3.Y - t4.Y)

现在只需继续这种方式即可处理所有8个皇后区。可能需要一些打字努力。

MySql fiddle