24 Matchstick Puzzle

Time limit1sMemory limit128 MB

Summary
Given N and K, remove exactly N matchsticks from a 3x3 grid of 24 matchsticks so that exactly K complete squares remain and every leftover stick belongs to some square.
Level

Medium6 of 10

Topics
Backtracking, Brute force, Simulation
Solved
No attempts yet

Problem

Consider a 3×3 grid puzzle made from 24 matchsticks. At first, every matchstick is placed as follows.

+--+--+--+
|..|..|..|
|..|..|..|
+--+--+--+
|..|..|..|
|..|..|..|
+--+--+--+
|..|..|..|
|..|..|..|
+--+--+--+

Two consecutive - characters represent one horizontal matchstick, and two consecutive | characters represent one vertical matchstick. A + marks a point where matchstick endpoints can meet, and . marks empty space.

Initially, the grid contains 14 squares: nine 1×1 squares, four 2×2 squares, and one 3×3 square.

You are given integers N and K. Remove exactly N matchsticks so that all of the following conditions hold.

  • Exactly N matchsticks are removed.
  • The remaining grid contains exactly K completed squares.
  • Every remaining matchstick is used as a side of at least one completed square.

Write a program that prints one grid satisfying these conditions.

Input

The first line contains integers N and K. (1 ≤ N < 24, 1 ≤ K < 14)

N is the number of matchsticks to remove, and K is the number of squares that must remain.

Output

Print a grid satisfying the conditions in 10 lines.

  1. Print + at every point where matchstick endpoints can meet, even if no matchstick touches that point.
  2. Print . at every position where no matchstick is placed.
  3. Print one horizontal matchstick as two consecutive - characters.
  4. Print one vertical matchstick as two consecutive | characters.

Every input is guaranteed to have at least one valid answer. If there are multiple valid grids, you may print any one of them.

Examples3

  1. Example 1

    Input
    20 1
    
    Expected output
    +--+..+..+
    |..|......
    |..|......
    +--+..+..+
    ..........
    ..........
    +..+..+..+
    ..........
    ..........
    +..+..+..+
    
  2. Example 2

    Input
    5 4
    
    Expected output
    +--+--+--+
    |..|..|..|
    |..|..|..|
    +--+--+..+
    |.....|..|
    |.....|..|
    +--+--+..+
    |........|
    |........|
    +--+--+--+
    
  3. Example 3

    Input
    4 6
    
    Expected output
    +--+--+--+
    |..|..|..|
    |..|..|..|
    +--+--+..+
    |..|..|..|
    |..|..|..|
    +--+--+..+
    |........|
    |........|
    +--+--+--+