This page is still under construction.

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

Jawbreak

Time limit2sMemory limit512 MB

Summary
Remove groups of at least 3 same-coloured connected balls to maximize the sum of squared group sizes plus a 1000 point clearing bonus.
Level

Medium7 of 10

Topics
Backtracking, Simulation, Brute force
Solved
No attempts yet

Problem

Jawbreaker is a simple game that used to come with PDAs and mobile phones. The game starts with a board full of coloured balls. The player picks a group of same-coloured balls that holds at least 3 balls, and the whole group disappears at once. A group here means every same-coloured ball connected to the picked one, so the player cannot remove only part of a group.

When balls disappear, the balls above them in the same column fall down, and empty space is left at the top of the column. If a column becomes completely empty, every column to its right shifts left, and empty space is left on the right side of the board.

The score starts at 0. Each move adds the square of the number of removed balls to the score. Removing every ball from the board wins the game and adds a bonus of 1000 points. The game is over when no group of 3 or more balls remains.

Two balls are neighbours when they touch above, below, to the left, or to the right. Balls that touch only diagonally are not neighbours.

You are given an n×nn \times n board with mm colours. Write a program that finds the maximum score reachable from that board.

Input

The first line has the board size nn and the number of colours mm. (1≤n≤81 \le n \le 8, 1≤m≤41 \le m \le 4)

Each of the next nn lines has nn characters describing the initial board. Each character is a digit between 11 and mm and gives the colour of the ball on that square.

Output

Print the maximum score reachable from the initial board.

Examples2

  1. Example 1

    Input
    3 3
    113
    211
    112
    
    Expected output
    36
    
  2. Example 2

    Input
    4 3
    3222
    3211
    2212
    3322
    
    Expected output
    1106