Neutral Ground

시간 제한1초메모리 제한1024 MB

요약
두 군대가 배치된 격자에서 각 칸의 병력 비용이 주어질 때, 어떤 A에서 어떤 B로도 경로가 통하지 않도록 막을 칸을 골라 총비용을 최소화한다.
난이도

보통10점 중 6점

유형
최소 신장 트리, 그래프, 그리디, 배열
정답자
아직 제출이 없습니다

문제

Two kingdoms had been at war for a long time, until the emperor intervened to bring an end to the conflict. The territory in question comprises an MM by NN rectangular grid. At the emperor's insistence, the two kings have withdrawn their troops until no two opposing troops are in adjacent squares of the map (adjacent being horizontal or vertical -- diagonal is not considered).

The emperor proposes to designate certain squares of the map as neutral territory. Neither king will be allowed to move troops into those squares, and the emperor's own forces will patrol them to be sure that both kings observe these rules.

The emperor is frugal and does not want to commit more soldiers to this effort than absolutely necessary. His generals have marked each square of the map with the number of soldiers required to secure that square. What remains is to choose which of those squares should be patrolled.

Write a program to determine the minimum number of soldiers that the emperor will need to be deploy to guarantee that the troops of one kingdom cannot move, in one or more steps, into squares occupied by the troops of the second kingdom (moving horizontally or vertically) without encountering the emperor's own soldiers.

입력

Input begins with a line containing 22 integers, ww and hh, denoting the width and height of the map. 1≤w,h≤401 \leq w, h \leq 40.

This is followed by hh lines. Each line contains ww characters, left justified. These characters will be 'A' or 'B', designating a position held by king A or king B, or a single numeric digit, designating a currently unoccupied position that can be secured by the use of that number of soldiers. For example, a '2' would indicate that two soldiers must be deployed to that square to secure it against passage of other troops. A '0' indicates terrain that is impassible -- the emperor need not commit soldiers there because the kingdom troops cannot pass through that square.

No 'A' will be adjacent, horizontally or vertically, to any 'B'.

There will be at least one 'A' and one 'B' in the input.

출력

Print a single line containing an integer denoting the minimum number of soldiers that the emperor must deploy to guarantee that there is no open path between any 'A' position and any 'B' position, using any combination of horizontal or vertical moves.

예제2

  1. 예제 1

    입력
    8 5
    A11111AA
    AA7B111A
    111BB111
    11BBB111
    11BBB11B
    
    예상 출력
    13
    
  2. 예제 2

    입력
    25 6
    A211111321231111111111111
    2A2111110001111111BB11111
    AA211111000111111BBBB1111
    A2111114111411111BBBB1111
    AA2111110001111111BB11111
    AA21111110111111111111111
    
    예상 출력
    2