This page is still under construction.

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

Molecules, Molecules 2

Time limit1sMemory limit128 MB

Summary
The program decides whether neighboring grid atoms can be bonded so every C has 4 bonds, N has 3, O has 2, and H has 1.
Level

Medium7 of 10

Topics
Graph, Matrix
Solved
No attempts yet

Problem

Organic molecules get amazingly complex, and drawing them takes a great variety of shapes and conventions, especially if we want to show their three dimensional structure. If we restrict ourselves to reasonably simple compounds, meaning those with only single bonds between atoms, we can lay them out on a simple rectangular grid with every bond running horizontally or vertically. In such a molecule carbon bonds to 4 adjacent atoms, nitrogen to 3, oxygen to 2 and hydrogen to 1. Not every grid describes a valid molecule. Write a program that decides whether a given grid does.

An atom bonds only with the atoms directly above, below, left or right of it, and two adjacent atoms do not have to bond. The grid is valid when you can pick a set of bonds that gives every atom on the grid exactly the number of bonds it needs.

Input

The input consists of a series of candidate molecules drawn as grids. The first line for each molecule has two integers rr and cc (1≤r,c≤201 \le r, c \le 20), the number of rows and columns of the rectangle that follows. The next rr lines contain cc characters each, where each character is one of '.' (empty), 'H' (hydrogen), 'O' (oxygen), 'N' (nitrogen), 'C' (carbon). The input ends with a line holding two zeroes, 0 0. A molecule classified as valid need not be physically realisable, and one grid sometimes holds more than one molecule.

Output

For each candidate molecule, print one of these two lines:

Molecule <num> is valid.
Molecule <num> is invalid.

where <num> is a running number starting at 1.

Examples1

  1. Example 1

    Input
    3 4
    HOH.
    NCOH
    OO..
    3 4
    HOH.
    NCOH
    OONH
    4 10
    OOOOOOOOOO
    OOOOOOOOOO
    OOOONOOOOO
    OOOOOOOOOO
    2 3
    HOH
    HOH
    0 0
    
    Expected output
    Molecule 1 is valid.
    Molecule 2 is invalid.
    Molecule 3 is invalid.
    Molecule 4 is valid.