This page is still under construction.

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

Landlocked

Time limit2sMemory limit256 MB

Summary
For each country letter on the grid, find the smallest number of country borders an 8-direction path crosses to reach water.
Level

Medium6 of 10

Topics
Shortest path, BFS, Graph, Matrix
Solved
No attempts yet

Problem

Canada is not landlocked. It touches the ocean, and in fact it touches three of them.

There are 46 countries in the world that are landlocked, Bolivia and Mongolia among them. A landlocked country does not touch an ocean, but it reaches one by passing through a single other country. A person in Mongolia reaches an ocean by passing through Russia.

Liechtenstein and Uzbekistan are the only two land-landlocked countries in the world. They are landlocked, and every country that surrounds them is landlocked as well. Anyone leaving Uzbekistan therefore passes through at least two different countries before reaching an ocean.

Given a map, determine how landlocked each country is. A country is not landlocked, recorded as 00, if any of its cells has water in a horizontally, vertically, or diagonally adjacent cell. If a country is landlocked, its value is the smallest number of borders that must be crossed to travel from the country to water. Each step of the journey moves to a horizontally, vertically, or diagonally adjacent cell. Crossing a border means stepping from a cell of one country into a cell of a different country. A water cell belongs to no country, so stepping into water does not count as crossing a border.

A country may be split into several pieces, the way a country made of islands is. Its value is then the smallest of the values computed for its pieces.

Input

The first line contains NN and MM. (1≤N,M≤10001 \le N, M \le 1000)

Each of the next NN lines contains MM uppercase letters with no spaces between them. Each country is written with its own letter. The letter W is not used as a country name; it marks the water of an ocean, a sea, or a lake. The map contains at least one water cell.

Output

For each country on the map, print one line holding the letter of the country and its value, separated by a single space. Print the countries in alphabetical order.

Examples2

  1. Example 1

    Input
    7 10 
    WWWWWCCDEW
    WWWWCCEEEW
    WTWWWCCCCW
    WWFFFFFFWW
    WWFAAAAFWW
    WWFABCAFFW
    WWFAAAAFWW
    
    Expected output
    A 1
    B 2
    C 0
    D 1
    E 0
    F 0
    T 0
    
  2. Example 2

    Input
    5 5
    AAAAA
    ABBBA
    ABWBA
    ABBBA
    AAAAA
    
    Expected output
    A 1
    B 0