#C5125. Longest Unique Path in a Grid

    ID: 48740 Type: Default 1000ms 256MiB

Longest Unique Path in a Grid

Longest Unique Path in a Grid

You are given a grid of size \( M \times N \) consisting of uppercase English letters. Your task is to find the length of the longest path in the grid such that all the characters on the path are unique. From any cell, you can move in one of the four directions: up, down, left, or right. Each cell may be visited at most once in a path.

Note: Two cells are considered adjacent if they share a common edge. The uniqueness constraint applies to the characters encountered along the path.

Input constraints: \(1 \leq M, N \leq 10\) (the grid is small enough for a backtracking solution).

Example 1:

Input:
4 4
A B C D
E F G H
I J K L
M N O P

Output: 16

</p>

Example 2:

Input:
2 3
A A C
B B D

Output: 4

</p>

inputFormat

The first line contains two integers \(M\) and \(N\) which denote the number of rows and columns in the grid respectively. The next \(M\) lines each contain \(N\) uppercase letters separated by spaces representing the grid.

Example:

4 4
A B C D
E F G H
I J K L
M N O P

outputFormat

Output a single integer which is the length of the longest path where all characters are unique.

Example:

16
## sample
4 4
A B C D
E F G H
I J K L
M N O P
16