Sure! Below is a C++ program that solves the problem described. The program uses Depth-First Search (DFS) with memoization to efficiently find the longest path of consecutive letters starting from 'A' in each provided grid.
Explanation:
-
Input Handling:
- The program reads multiple test cases until it encounters
H = 0 and W = 0, which signifies the end of input.
- For each test case, it reads
H lines with W uppercase letters each to form the grid.
-
DFS with Memoization:
- The
dfs function computes the longest path starting from a given cell (i, j). It utilizes memoization (dp array) to store already computed results, avoiding redundant calculations.
- For each cell containing 'A', the program initiates a DFS to find the maximum possible path length starting from that cell.
-
Direction Handling:
- The program considers all 8 possible directions (horizontal, vertical, and diagonal) to move from the current cell to adjacent cells.
-
Output:
- For each test case, the program outputs the case number and the length of the longest path found, formatted as
"Case C: X".
C++ Code:
#include <bits/stdc++.h>
using namespace std;
// Directions: 8 neighbors
const int dx[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
const int dy[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
// Global variables for grid and memoization
int H, W;
vector<string> grid;
vector<vector<int>> dp_cache;
// DFS function to find the maximum path starting at (i, j)
int dfs(int i, int j) {
if (dp_cache[i][j] != -1) {
return dp_cache[i][j];
}
dp_cache[i][j] = 1; // At least the current cell
for(int dir = 0; dir < 8; dir++) {
int ni = i + dx[dir];
int nj = j + dy[dir];
if(ni >=0 && ni < H && nj >=0 && nj < W) {
if(grid[ni][nj] == grid[i][j] + 1) {
dp_cache[i][j] = max(dp_cache[i][j], 1 + dfs(ni, nj));
}
}
}
return dp_cache[i][j];
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int case_num = 1;
while(cin >> H >> W){
if(H ==0 && W ==0){
break;
}
grid.assign(H, "");
for(int i=0; i<H; i++) {
cin >> grid[i];
// Ensure that each row has exactly W characters
while((int)grid[i].size() < W){
grid[i] += ' ';
}
grid[i] = grid[i].substr(0, W);
}
// Initialize dp_cache with -1
dp_cache.assign(H, vector<int>(W, -1));
int max_path = 0;
for(int i=0; i<H; i++) {
for(int j=0; j<W; j++) {
if(grid[i][j] == 'A') {
max_path = max(max_path, dfs(i, j));
}
}
}
cout << "Case " << case_num++ << ": " << max_path << "\n";
}
}
How to Use:
-
Input Format:
- For each test case, input two integers
H and W representing the height and width of the grid.
- Followed by
H lines, each containing W uppercase letters.
- The input ends when
H = 0 and W = 0.
-
Running the Program:
-
Example:
Input:
4 3
ABE
CFG
BDH
ABC
0 0
Output:
Case 1: 4
This output matches the example provided, indicating that the longest path starting from 'A' has a length of 4.