Advertisement
tepyotin2

Letters

May 1st, 2025
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int n, m;
  6. char grid[21][21];
  7. bool visited[27];
  8. int dx[] = {-1, 1, 0, 0};
  9. int dy[] = {0, 0, 1, -1};
  10. int ans;
  11.  
  12. void dfs(int x, int y, int counter){
  13.     if(visited[grid[x][y]-'A'] || x<0 || x>=n || y<0 || y>=m){
  14.         return;
  15.     }
  16.     //visited[x][y] = true;
  17.     //counter++;
  18.     visited[grid[x][y]-'A'] = true;
  19.     ans = max(ans, counter);
  20.     for(int i=0; i<4; i++){
  21.         int nx = x+dx[i];
  22.         int ny = y+dy[i];
  23.         if(!visited[grid[nx][ny]-'A'] && nx>=0 && nx<n && ny>=0 && ny<m){
  24.             counter++;
  25.             //cout << "nx: " << nx << ", ny: " << ny << ", grid[nx][ny]: " << grid[nx][ny] << ", counter: " << counter << '\n';
  26.             //visited[grid[x][y]-'A'] = true;a
  27.             dfs(nx, ny, counter);
  28.             counter--;
  29.             //visited[grid[x][y]-'A'] = false;
  30.         }
  31.     }
  32.     //counter--;
  33.     visited[grid[x][y]-'A'] = false;
  34. }
  35.  
  36. int main(){
  37.     //freopen("letters.in", "r", stdin);
  38.    
  39.     cin >> n >> m;
  40.     string s;
  41.     for(int i=0; i<n; i++){
  42.         cin >> s;
  43.         for(int j=0; j<m; j++){
  44.             grid[i][j] = s[j];
  45.         }
  46.     }
  47.     //for(int i=0; i<n; i++){
  48.         //for(int j=0; j<m; j++){
  49.             //cout << "i: " << i << ", j: "<< j << ", grid[i][j]: " << grid[i][j] << '\n';
  50.             //memset(visited, false, sizeof(visited));
  51.             //dfs(i, j, 1);
  52.         //}
  53.     //}
  54.     dfs(0, 0, 1);
  55.     cout << ans << '\n';
  56.    
  57.     return 0;
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement