This page is still under construction.

Parts of this page are still being built. What you see may change.

CrossNumber

Time limit1sMemory limit128 MB

Summary
Fill a digit-grid puzzle where each across and down run must match a given digit sum, always leaving a word with one blank cell to solve.
Level

Medium6 of 10

Topics
Simulation, Implementation, Greedy, Array
Solved
No attempts yet

Problem

You have bet a friend that you can write a program to solve a newspaper CrossNumber puzzle faster than she can solve it by hand.

The puzzle is similar to a crossword, except that each cell contains a digit from 00 to 99 instead of a letter. Each clue gives the sum of the digits in the corresponding word. So that it never frustrates the reader, the puzzle is constructed so that throughout the solving process there is always a word with exactly one unfilled cell.

Input

The input consists of several test cases. Each test case begins with an integer NN (2≤N≤1002 \le N \le 100) on a line by itself, giving the number of rows and columns of the square puzzle.

Each test case is described by:

  • NN rows of NN characters each, giving the puzzle grid. The character . denotes an unfilled cell, the character # denotes a black cell, and a digit 0 to 9 denotes the value already assigned to that cell.
  • a line containing the word Across.
  • one line for each across clue, containing three integers x y sum. Here x and y are the column and row numbers (1≤x,y≤N1 \le x, y \le N), and sum is the sum of the digits in that across (or down) word.
  • a line containing the word Down.
  • one line for each down clue, formatted like an across clue.

Each maximal horizontal or vertical run of non-black cells whose length is at least two has exactly one clue, listed for its top-left square, even if all of its cells are already filled by hints.

A line containing a single 0 marks the end of the input and should not be processed.

Output

For each test case, print the solved grid in the same format (NN rows of NN characters). Separate the outputs of consecutive puzzles with a single blank line.

The puzzle is guaranteed to have a unique solution.

Examples3

  1. Example 1

    Input
    5
    #####
    #..3#
    ##5##
    #4.9#
    #####
    Across
    2 2 10
    2 4 15
    Down
    3 2 14
    3
    #.9
    ###
    #74
    Across
    2 3 11
    2 1 10
    Down
    0
    
    Expected output
    #####
    #073#
    ##5##
    #429#
    #####
    
    #19
    ###
    #74
    
  2. Example 2

    Input
    2
    1.
    ..
    Across
    1 1 3
    1 2 7
    Down
    1 1 4
    2 1 6
    0
    
    Expected output
    12
    34
    
  3. Example 3

    Input
    3
    .46
    1.5
    90.
    Across
    1 1 12
    1 2 9
    1 3 13
    Down
    1 1 12
    2 1 7
    3 1 15
    0
    
    Expected output
    246
    135
    904