#C11980. Longest Unique Path in Grid

    ID: 41356 Type: Default 1000ms 256MiB

Longest Unique Path in Grid

Longest Unique Path in Grid

You are given a grid with R rows and C columns, where each cell contains an uppercase letter. Your task is to determine the length of the longest path such that no letter appears more than once in the path. From any cell, you can move in the four cardinal directions: up, down, left, or right.

Formally, if the grid is denoted by \(grid\) and a path is a sequence of cells \((i_1,j_1), (i_2,j_2), \dots, (i_k,j_k)\) where each adjacent pair of cells are neighbors (i.e., differ by 1 in either row or column), the following must hold for a valid path: \[ \text{For all } 1 \leq p < q \leq k, \quad grid[i_p][j_p] \neq grid[i_q][j_q]. \] The output is the maximum possible value of \(k\).

Note: The path can start at any cell and does not have to cover all cells.

inputFormat

The input is read from standard input (stdin) and has the following format:

  • The first line contains two integers \(R\) and \(C\), the number of rows and columns.
  • The following \(R\) lines each contain a string of length \(C\) representing a row of the grid. Each character is an uppercase letter.

outputFormat

Output a single integer to standard output (stdout), which is the length of the longest path with no repeated characters.

## sample
3 4
ABCD
EFGH
IJKL
12

</p>