#K60577. Longest Unique Character Path in a Grid

    ID: 31117 Type: Default 1000ms 256MiB

Longest Unique Character Path in a Grid

Longest Unique Character Path in a Grid

Given a grid with N rows and M columns filled with lowercase English letters, your task is to determine the length of the longest path in the grid such that every character encountered in the path is unique. You may move from one cell to an adjacent cell (up, down, left, or right) and you can start from any cell in the grid.

More formally, you wish to find the maximum integer \(L\) for which there exists a sequence of cells \((i_1,j_1), (i_2,j_2), \dots, (i_L,j_L)\) satisfying:

$$ \text{For all } 1 \leq k < L, \; (i_{k+1},j_{k+1}) \text{ is adjacent to } (i_k,j_k), \quad \text{and} \quad grid[i_k][j_k] \neq grid[i_m][j_m] \text{ for all } k \neq m. $$

Your solution should compute and output this maximum path length.

inputFormat

The input is provided via standard input (stdin) and has the following format:

  • The first line contains two space-separated integers \(N\) and \(M\), representing the number of rows and columns respectively.
  • Each of the next \(N\) lines contains a string of exactly \(M\) lowercase letters, which represents a row of the grid.

outputFormat

Output a single integer (printed to standard output, stdout) that represents the length of the longest path in the grid where no character is repeated.

## sample
3 4
abcd
efgh
ijkl
12