fork download
  1. // 解を列挙する関数
  2. let solve xBlockNum yBlockNum =
  3. let [xLen; yLen] = [xBlockNum; yBlockNum] |> List.map (fun n -> n * 2 - 1)
  4. let markingNum = xBlockNum * yBlockNum * 2 - 1
  5. let directions = [1, 0; 0, 1; -1, 0; 0, -1]
  6. let memo = System.Collections.Generic.HashSet(HashIdentity.Structural)
  7.  
  8. let getNext markedSet candidates =
  9. candidates |> Seq.map (fun ((x, y), (dx, dy)) ->
  10. let nx, ny = x + dx, y + dy
  11. let newMarked = markedSet |> Set.add (x, y) |> Set.add (nx, ny)
  12. directions |> List.choose (fun (dx, dy) ->
  13. if 1 <= nx + dx && nx + dx <= xLen && 1 <= ny + dy && ny + dy <= yLen
  14. then Some((nx + dx, ny + dy), (dx, dy)) else None)
  15. |> Seq.append candidates
  16. |> Seq.filter (fun ((x, y), (dx, dy)) -> Set.contains (x + dx, y + dy) newMarked |> not)
  17. |> fun nextCandidates -> newMarked, nextCandidates)
  18.  
  19. let rec solve markedSet candidates = seq {
  20. if memo.Add markedSet then
  21. if Set.count markedSet = markingNum then yield markedSet
  22. else yield! getNext markedSet candidates |> Seq.collect ((<||) solve) }
  23.  
  24. solve (set [1, 1]) [(2, 1), (1, 0); (1, 2), (0, 1)]
  25. |> Seq.map (fun result ->
  26. [for y in 0 .. yLen + 1 ->
  27. [for x in 0 .. xLen + 1 -> if Set.contains (x, y) result then "*" else "-"]])
  28.  
  29. // 解を10個表示
  30. solve 4 4 |> Seq.take 10 |> Seq.iter (fun result ->
  31. result |> Seq.iter (String.concat "" >> printfn "%s"); printfn "")
Success #stdin #stdout 0.22s 12904KB
stdin
Standard input is empty
stdout
---------
-*******-
-*-*-*-*-
-*-*-*-*-
-*-*-*-*-
-*-*-*-*-
-*-*-*-*-
-*-*-*-*-
---------

---------
-*******-
-*-*-*-*-
-*-*-*-*-
-*-*-*-*-
-*-*-*-*-
-*-*-*---
-*-*-***-
---------

---------
-*******-
-*-*-*-*-
-*-*-*-*-
-*-*-*-*-
-*-*-*-*-
-*-*---*-
-*-***-*-
---------

---------
-*******-
-*-*-*-*-
-*-*-*-*-
-*-*-*-*-
-*-*-*-*-
-*-*-----
-*-*****-
---------

---------
-*******-
-*-*-*-*-
-*-*-*-*-
-*-*-*-*-
-*-*-*-*-
-*-*---*-
-*-*-***-
---------

---------
-*******-
-*-*-*-*-
-*-*-*-*-
-*-*-*---
-*-*-***-
-*-*-*-*-
-*-*-*-*-
---------

---------
-*******-
-*-*-*-*-
-*-*-*-*-
-*-*-*---
-*-*-***-
-*-*-*---
-*-*-***-
---------

---------
-*******-
-*-*-*-*-
-*-*-*-*-
-*-*-*---
-*-*-***-
-*-*---*-
-*-***-*-
---------

---------
-*******-
-*-*-*-*-
-*-*-*-*-
-*-*-*---
-*-*-***-
-*-*-----
-*-*****-
---------

---------
-*******-
-*-*-*-*-
-*-*-*-*-
-*-*-*---
-*-*-***-
-*-*---*-
-*-*-***-
---------