This page is still under construction.

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

Another Brick in the Wall

Time limit1sMemory limit128 MB

Summary
Try pulling each brick and report the largest total length of bricks that fall once every support below them is gone.
Level

Medium6 of 10

Topics
Graph, BFS, Brute force, Simulation
Solved
No attempts yet

Problem

After years of laying bricks, you have been asked to analyze how unstable a brick wall is. The instability of a wall is approximated by the largest damage the wall takes when one brick is pulled out.

A brick falls when every brick that was directly underneath it is gone. If the space under a brick is only partly empty, the brick does not fall. A brick that has fallen no longer holds up the bricks above it, so a collapse spreads. The bricks in the bottom row sit on the ground and never fall.

Given the layout of every brick in a wall, find the instability of the wall.

Input

The input contains several test cases. The first line of each test case holds the height MM and the width NN of the wall. (1≤M,N≤1001 \le M, N \le 100)

Each of the next MM lines is a string of NN digits describing one row of the wall. The first of those lines is the top row of the wall and the MM-th one is the row that touches the ground. Inside a row, one brick is written as a substring whose digits are all the same and equal to its length. For example, 333 and 22 are one brick of length 3 and one brick of length 2, while 111 is three bricks of length 1. The digit 0 means that place of the wall is empty. Every brick has height 1.

The input ends with a line containing 0 0. The input is always correct, so both of the following hold.

  1. No brick has a length that disagrees with the digits it is made of, such as 222 inside the row 12221.
  2. No brick falls before a brick is pulled out.

Output

For each test case, print on one line the largest total length of the bricks that fall when one brick is pulled out. The length of the brick that was pulled out counts toward the total.

Examples1

  1. Example 1

    Input
    4 5
    33322
    22333
    33322
    22333
    4 6
    122333
    444422
    111111
    333333
    3 3
    022
    220
    111
    0 0
    
    Expected output
    5
    8
    4