#C11167. Longest Alphabetical Path in Grid

    ID: 40453 Type: Default 1000ms 256MiB

Longest Alphabetical Path in Grid

Longest Alphabetical Path in Grid

You are given a grid with N rows and M columns, where each cell contains a lowercase English letter. Your task is to find the length of the longest path such that consecutive characters in the path follow each other in alphabetical order. Note that the sequence wraps around from \(z\) to \(a\).

The path can start at any cell, and you may move to an adjacent cell in one of the eight directions (horizontally, vertically, or diagonally). Each cell can be visited at most once per path.

Input constraints (example):

  • 1 \(\le N, M \le 100\)
  • Each grid row is a string of exactly \(M\) lowercase English letters.

inputFormat

The input is read from stdin and contains multiple test cases. The first line of the input contains an integer \(T\) representing the number of test cases. For each test case:

  • The first line contains two space-separated integers \(N\) and \(M\), which represent the number of rows and columns of the grid, respectively.
  • The following \(N\) lines each contain a string of length \(M\), representing one row of the grid.

outputFormat

For each test case, output a single integer on a new line representing the length of the longest alphabetical path found in the grid.

## sample
1
3 4
abcd
bcda
dabc
4

</p>