#K41567. Maximum Unique Gems

    ID: 26894 Type: Default 1000ms 256MiB

Maximum Unique Gems

Maximum Unique Gems

You are given an ( m \times n ) grid where each cell contains an integer representing the type of gem at that cell. Starting from any cell, you may move in the four cardinal directions (up, down, left, right). However, you can only move to a cell if the gem in that cell has not been collected yet. Formally, if you are at cell ( (i, j) ), you can move to cell ( (i+1, j) ), ( (i-1, j) ), ( (i, j+1) ), or ( (i, j-1) ) provided that the gem in the target cell is not already in your collection. Your task is to find the maximum number of unique gems that can be collected during such a journey. The grid’s rows and columns are 0-indexed.

inputFormat

The input is read from standard input (stdin) and follows the format below:

The first line contains two space-separated integers ( m ) and ( n ), denoting the number of rows and columns of the grid, respectively. Each of the following ( m ) lines contains ( n ) space-separated integers representing the gem types in that row.

For example: 3 3 1 2 3 4 5 6 7 8 9

outputFormat

Output a single integer, which is the maximum number of unique gems that can be collected under the movement restrictions. The result should be printed to standard output (stdout).## sample

3 3
1 2 3
4 5 6
7 8 9
9