1
0

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 queens問題を解く [python]

Last updated at Posted at 2025-03-09

N queens問題を解きます。8 queens問題として知られていますが、ここでは、Nとし、プログラムはN=8とします。
(N*N)の桝目のチェスのクイーンが互いに相手を取らないようにN駒並べる局面を出力します。
pythonで書かれています。

nqueens.py
#!/usr/bin/python3
N=8 # 盤の桝目とQueenの数
a=[True]*N
b=[True]*(2*N-1)
c=[True]*(2*N-1)
x=[0]*N
solution=0

def found():
    global solution
    solution+=1
    print(f"\n{solution}\n")
    for i in range(N):
        for j in range(N):
            print(" Q" if x[i]==j else " .",end='')
        print("")

def _try(i):
    global a,b,c
    for j in range(N):
        if a[j] and b[i+j] and c[i-j+N-1]:
            x[i]=j
            if i<N-1:
                a[j],b[i+j],c[i-j+N-1]=False,False,False
                _try(i+1)
                a[j],b[i+j],c[i-j+N-1]=True,True,True
            else:
                found()

if __name__=='__main__':
    _try(0)
    exit(0)
出力
$ ./nqueens.py
 解 1

 Q . . . . . . .
 . . . . Q . . .
 . . . . . . . Q
 . . . . . Q . .
 . . Q . . . . .
 . . . . . . Q .
 . Q . . . . . .
 . . . Q . . . .

 解 2

(略)
1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?