#C2583. Longest Unique Path in a Grid

    ID: 45915 Type: Default 1000ms 256MiB

Longest Unique Path in a Grid

Longest Unique Path in a Grid

You are given a grid of characters with R rows and C columns. Your task is to find the length of the longest path where each cell visited contains a unique letter. You can move in four directions (up, down, left, right) from a cell. The path can start from any cell, and you cannot visit a cell that contains a letter that has already appeared in the current path.

The answer should be computed by exploring all possible paths, ensuring that letters do not repeat. The final output is the maximum number of cells that can be visited under these conditions.

Note: All mathematical expressions, if needed, must be formatted with LaTeX. For example, the grid dimensions can be expressed as $R \times C$, and the condition for unique letters can be written as: if $a \in S$, then $a \notin S$ for the current path set $S$.

inputFormat

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

  • The first line contains two integers, R and C — the number of rows and columns in the grid.
  • The following R lines each contain a string of C lowercase letters representing a row of the grid.

outputFormat

Output to stdout a single integer which is the length of the longest path containing unique letters.

## sample
2 2
ab
cd
4