用haskell實現的八皇后程式

2021-09-06 06:19:52 字數 2173 閱讀 4095

用haskell解八皇后問題,haskell才是最精練的程式:

main  = print $ queens 8boardsize = 8queens 0 =

queens n = [ x : y | y <- queens (n-1), x <- [1..boardsize], safe x y 1]

where

safe x n =true

safe x (c:y) n = and [ x /= c , x /= c + n , x /= c - n , safe x y (n+1)]

執行結果:

[[4,2,7,3,6,8,5,1],[5,2,4,7,3,8,6,1],[3,5,2,8,6,4,7,1],[3,6,4,2,8,5,7,1],[5,7,1,3,8,6,4,2],[4,6,8,3,1,7,5,2]  ... ... ... ... 5,7,2,6,3,1,4,8]]

另外一種用到了monad的源程式:

import control.monad

queens n = foldm (\y _ -> [ x : y | x <- [1..n], safe x y 1]) [1..n]

safe x n =true

safe x (c:y) n = and [ x /= c , x /= c + n , x /= c - n , safe x y (n+1)]

main = mapm_ print $ queens 8

執行結果:

[4,2,7,3,6,8,5,1]

[5,2,4,7,3,8,6,1]

[3,5,2,8,6,4,7,1]

[5,7,2,6,3,1,4,8]

albertlee在這篇用 python 秒掉八皇后問題!中給出的haskell程式:

import control.monad

import control.monad.writer

import data.list

diagonal (x1,y1) (x2,y2) = x1 + y1 == x2 +y2

|| x1 - y1 == x2 -y2

nqueens n = execwriter $ f [1..n] 1

where f _ ps =tell [ps]

f cs r ps = form_ cs $ \c ->;

unless (any (diagonal (r,c)) ps) $

f (delete c cs) (r + 1) ((r,c):ps)

main = print $ nqueens 4

給出的**:

module

main where

import data.list

queue :: int -> int ->[[int]]

queue m 1 = [ [x] | x <- [1..m] ]

queue m n = concatmap put $ filter putable $ queue m (n-1)

where

putable xs = (safe_places xs /=)

put xs =map (:xs) $ safe_places xs

safe_places xs = [1..m] \\ (concatmap (\(x,y) -> [x-y,x,x+y]) $ zip xs [1..])

main =do

putstrln $ "there are " ++ show(length result) ++ " solutions in total"mapm_ (print.zipwith (\x y -> x:show y) ['a'..'h']) result

where

result = queens 8queens 0 =

queens n = [ q:b | b <- queens (n-1), q <- [1..8], safe q b ]

safe q b = and [ not (checks q b i) | i <- [0..(length b-1)] ]

checks q b i = q==b!!i || abs(q - b!!i)==i+1

haskell了解得還太少,暫時這些**都看不懂,先收集在這裡,以後慢慢理解。

用遞迴列舉實現八皇后問題

include using namespace std int total 0 判斷row行line列是否可以放皇后 bool iscan int row int line int chess 8 8 判斷左上是否有皇后 for i row j line i 0 j 0 i j 判斷右上是否有皇后 ...

用C 語言實現八皇后問題

一 問題描述 八皇后問題是乙個以西洋棋為背景的問題 如何能夠在 8 8 的西洋棋棋盤上放置八個皇后,使得任何乙個皇后都無法直接吃掉其他的皇后?為了達到此目的,任兩個皇后都不能處於同一條橫行 縱行或斜線上。二 整體設計思路 1.用web控制項table實現棋盤的布局 table控制項在後台用 生成,多...

八皇后問題(用c語言實現)

八皇后問題 輸入 乙個數字n,表示在n n的 上,合理的擺放n個皇后。輸出 輸出n個皇后所能擺放的全部可能性,0 該位置不擺放皇后,1 在該位置擺放皇后。樣例輸入 1 no answer 2 no answer 4 0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 1 0 1 ...