#K63087. Longest Path on a Grid
Longest Path on a Grid
Longest Path on a Grid
You are given an n×m grid of uppercase Latin letters and a starting position (start_x, start_y). Your task is to determine the length of the longest path you can take from the starting cell by moving to adjacent cells (up, down, left, right) without revisiting any cell. In other words, find the maximum number of cells that can be visited in a single journey starting from the given cell.
The answer is represented by an integer. Mathematically, if we define a path P as a sequence of distinct cells, the answer is the maximum k such that P = [p_1, p_2, ..., p_k] with p_1 equal to the starting position, and each consecutive pair of cells share a common edge. Formally, the goal is to compute:
$$\text{ans} = \max\{ k \mid p_1=(start_x, start_y),\ p_i \text{ adjacent to } p_{i+1},\ \forall i \}\ $$It is guaranteed that the grid is small and an exhaustive search using backtracking (DFS) is feasible.
inputFormat
The first line contains two integers n
and m
representing the number of rows and columns of the grid respectively.
The next n
lines each contain a string of length m
consisting of uppercase letters, representing the grid.
The last line contains two integers start_x
and start_y
indicating the starting cell's row and column (0-indexed).
outputFormat
Output a single integer representing the length of the longest path from the designated starting cell.
## sample3 3
ABC
DEF
GHI
1 1
9