This page is still under construction.

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

Molecules, Molecules

Time limit1sMemory limit128 MB

Summary
Decide whether grid atoms can be linked to orthogonal neighbors so each carbon, nitrogen, oxygen, and hydrogen has 4, 3, 2, and 1 bonds.
Level

Medium7 of 10

Topics
Graph
Solved
No attempts yet

Problem

Organic molecules can be amazingly complex, and picturing them takes a great variety of shapes and conventions, especially when we want to show details of their 3-dimensional structure. If we stay with reasonably simple compounds, meaning those with only single bonds between atoms, we can draw them on a rectangular grid with every bond running horizontally or vertically. In such a molecule carbon is bonded to four adjacent atoms, nitrogen to 3, oxygen to 2 and hydrogen to 1.

A bond joins two atoms that sit in horizontally or vertically neighbouring cells, and the same pair of atoms is bonded at most once. Neighbouring atoms are not forced to bond. A grid represents a valid molecule when the bonds can be chosen so that every atom reaches exactly its own number of bonds.

Not every grid represents a valid molecule. Write a program that decides whether a given grid does.

Input

The input holds a series of possible molecules drawn as grids. The first line for each molecule holds two integers r and c (1≤r,c≤51 \le r, c \le 5), the number of rows and columns of the rectangle that follows. The next r lines contain c characters each, taken from . (empty), H (hydrogen), O (oxygen), N (nitrogen) and C (carbon). The input ends with a line containing two zeroes.

A grid classified as valid need not be physically realisable, and one grid may hold more than one molecule.

Output

For each potential molecule, print one of the following 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
    2 3
    HOH
    HOH
    0 0
    
    Expected output
    Molecule 1 is valid.
    Molecule 2 is invalid.
    Molecule 3 is valid.