10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

組合せ最適化でN Queen問題を解く

10
Last updated at Posted at 2016-05-29

N Queen問題とは

N × Nの盤上に、N個のクイーンを配置する。このとき、
どの駒も他の駒に取られるような位置においてはいけない。

この問題も組合せ最適化で解けます。

定式化

目的関数 なし
変数 $x_j \in \{0, 1\} ~ ~ \forall j \in 各マス$ そのマスに置くかどうか
制約条件 $\sum_{j \in 各マス~~~~~}{\{x_j|縦がi列\}} = 1 ~ ~ \forall i \in \{0, \cdots, N-1\}$ 1列に1つ
$\sum_{j \in 各マス~~~~~}{\{x_j|横がi行\}} = 1 ~ ~ \forall i \in \{0, \cdots, N-1\}$ 1行に1つ
$\sum_{j \in 各マス~~~~~}{\{x_j|縦+横がi\}} \le 1 ~ ~ \forall i \in \{0, \cdots, 2 N-2\}$ 斜めは1つ以下
$\sum_{j \in 各マス~~~~~}{\{x_j|縦-横がi-N+1\}} \le 1 ~ ~ \forall i \in \{0, \cdots, 2 N-2\}$ 斜めは1つ以下

Pythonで解いてみる

定式化して解いてみましょう。

python3
from itertools import product

import matplotlib.pyplot as plt
import pandas as pd
from pulp import HiGHS, LpBinary, LpProblem, lpSum, value


def NQueen(N):
    r = range(N)
    m = LpProblem()
    df = pd.DataFrame(product(r, r), columns=["縦", "横"])
    df["X"] = m.add_variable_dict("x", df.index, cat=LpBinary)
    for i in r:
        m += lpSum(df[df.縦 == i].X) == 1
        m += lpSum(df[df.横 == i].X) == 1
    for i in range(2 * N - 1):
        m += lpSum(df[df.縦 + df.横 == i].X) <= 1
        m += lpSum(df[df.縦 - df.横 == i - N + 1].X) <= 1
    %time m.solve(HiGHS(msg=False))
    return df.X.apply(value).to_numpy().reshape(N, -1)


for N in [8, 16, 32, 64, 128]:
    plt.imshow(NQueen(N), cmap="gray", interpolation="none")
    plt.show()

>>>

CPU times: user 5.66 ms, sys: 1.44 ms, total: 7.1 ms
Wall time: 5.58 ms

CPU times: user 4.53 ms, sys: 402 μs, total: 4.93 ms
Wall time: 3.89 ms

CPU times: user 11.6 ms, sys: 735 μs, total: 12.3 ms
Wall time: 10.7 ms

CPU times: user 47.4 ms, sys: 1.91 ms, total: 49.3 ms
Wall time: 44.8 ms

CPU times: user 264 ms, sys: 239 ms, total: 503 ms
Wall time: 176 ms

image

以上

10
11
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?