You will be given a 2-dimensional grid of letters. Find the length of the longest path…
- User
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 Inputcopy Outputcopy 4 3 ABE CFG BDH ABC 0 0
Case 1: 4 Bu sualda #include <bits/stdc++.h>
using namespace std;
#define ll long long #define ld long double #define endl '\n' #define pb push_back #define speedyboy ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define all(x) x.begin() , x.end() #define F first #define S second #define pll pair<ll , ll> #define pss pair<string , string> #define YES cout << "YES" << endl; #define NO cout << "NO" << endl;
const ll sz = 1e2 + 5 , INF = 1e18 , MOD = 998244353; bool used[sz][sz]; char c[sz][sz]; const ll dx[] = {0 , 0 , -1 , 1 , -1 , -1 , 1 , 1} , dy[] = {1 , -1 , 0 , 0 , 1 , -1 , 1 , -1}; ll ans;
bool check(ll x , ll y , ll n , ll m){ return x >= 1 && x <= n && y >= 1 && y <= m; }
void dfs(ll x , ll y , ll n , ll m){ used[x][y] = true; ans++; for(ll i = 0 ; i < 8 ; i++){ ll nx = x + dx[i] , ny = y + dy[i]; if(check(nx , ny , n , m) && (ll)c[x][y] + 1 == (ll)c[nx][ny] && !used[nx][ny]) dfs(nx , ny , n , m); } }
ll i , j , k; void solve(){ ll n , m , w = 1; while(cin >> n >> m){ if(n == 0 && m == 0){ return; } memset(used , 0 , sizeof(used)); ll mx = -INF; for(i = 1 ; i <= n ; i++){ for(j = 1 ; j <= m ; j++){ cin >> c[i][j]; } } for(i = 1 ; i <= n ; i++){ for(j = 1 ; j <= m ; j++){ if(c[i][j] == 'A' && !used[i][j]){ ans = 0; dfs(i , j , n , m); mx = max(mx , ans); } } } cout << "Case " << w << ": " << mx << endl; w++; } }
signed main(){ speedyboy; ll t = 1; //cin >> t; while(t--){ solve(); } } kodumda nə səhv var?
- Assistant