Roman Corridor
Time limit1sMemory limit128 MB
Find a left-to-right path through the grid whose symbol string is a valid Roman numeral and has the smallest decimal value.
- Level
Medium7 of 10
- Topics
- DFS, Graph, String, Backtracking
- Solved
- No attempts yet
Problem
Roman numerals represent the natural numbers from to . They use the capital Latin letters I, V, X, L, C, D, M, whose "atomic" values are shown below.
To write a number , repeatedly take the largest atomic value that does not exceed , append its Roman form, and continue with . The symbols are written left to right with no spaces. For example, is written as CMXCIX (not IM, as one might guess).
You must walk through a rectangular corridor that is meters wide and meters long (, ). It is paved with square tiles, one meter on a side, and every tile shows one Roman symbol: I, V, X, L, C, D, or M. You move from tile to tile; from the current tile you may step only to a tile that shares an edge with it (up, down, left, or right — never diagonally). You enter from the leftmost column and must leave from the rightmost column.

Reading the symbols along your route from start to finish yields a string. Find a route whose string is a valid Roman numeral, and among all such routes report the one with the smallest value. If no route spells a valid Roman numeral, report that it is impossible.
Input
The first line contains two integers and , separated by one or more spaces. Each of the next lines contains characters describing one row of tiles.
Output
Print the smallest valid Roman numeral that can be spelled by a route from the leftmost column to the rightmost column. If no such route exists, print NO.