ABCPATH - ABC Path

You will be given a 2-dimensional grid of letters. Find the length of the longest path of consecutive letters, starting at 'A'. Paths can step from one letter in the grid to any adjacent letter (horizontally, vertically, or diagonally).

For example, in the following grid, there are several paths from 'A' to 'D', but none from 'A' to 'E':

ABC

One such path is:

path

Input

Each test case will start with a line contains two integers H, W the height and width of the grid respectively 1 <= H, W <= 50. Then H lines follow each of W uppercase letters only. Input terminates with H = 0 and W = 0.

Output

For each test case print “Case C: X” without quotes where C is the case number starting with 1 and X is the solution.

Example

Sample Input:
4 3
ABE
CFG
BDH
ABC
0 0

Sample Output:
Case 1: 4

Added by:Ali Arous
Date:2011-11-05
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64
Resource:FCIS Local Contest 2012

hide comments
2018-07-05 15:23:11
Simple DFS !! Just make once used characters unusable for further times as they can never help to reach farther than they did last time ;)
2018-05-25 16:51:05
Good one

Last edit: 2018-05-26 06:23:18
2018-02-04 07:39:51
use multi-source bfs
2018-01-17 18:00:13
AC in 1 go. :)
Simple recursion and memo..
2017-12-23 08:44:59
nice practice question:)
2017-08-28 07:57:04
Try this.

Input:
1 1
B
1 2
AA
1 1
A
1 1
B
5 3
ABF
CFG
OQP
DCB
PQA
0 0

Output:
Case 1: 0
Case 2: 1
Case 3: 1
Case 4: 0
Case 5: 4


Last edit: 2017-08-28 07:59:32
2017-08-13 09:27:12
used recursion :)
2017-07-30 19:56:06
Can not figure out an iterative solution though..
2017-07-22 19:22:59
simple DFS...dont forget the case when no 'A' is present!!
2017-06-18 11:22:10
just dfs with memo..otherwise tle. ;-)
© Spoj.com. All Rights Reserved. Spoj uses Sphere Engine™ © by Sphere Research Labs.