fork(1) download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int arr[50][50];
  4. //int info[50][50];
  5. int h,w;
  6. int func(int a,int b);
  7. int main()
  8. {
  9. int i,j,tc=0,temp,ans;
  10. vector<pair<int,int>> positions;
  11. char ch;
  12. while(cin>>h>>w){
  13. tc++;
  14. if(h==0 && w==0)
  15. return 0;
  16. for(i=0;i<h;i++){
  17. for(j=0;j<w;j++){
  18. cin>>ch;
  19. if(ch=='A')
  20. positions.push_back({i,j});
  21. arr[i][j]=int(ch)-64;
  22. }
  23. }
  24. ans=func(positions[0].first,positions[0].second);
  25. for(i=1;i<positions.size();i++){
  26. temp=func(positions[i].first,positions[i].second);
  27. if(temp>ans)
  28. ans=temp;
  29. }
  30. cout<<"Case "<<tc<<": "<<ans<<endl;
  31. positions.clear();
  32. }
  33. return 0;
  34. }
  35. int func(int a,int b)
  36. {
  37. int i,j,length,flag,ans=0;
  38. stack<pair<int,int>> stk;
  39. stk.push({a,b});
  40. while(!stk.empty()){
  41. flag=0;
  42. i=stk.top().first;
  43. j=stk.top().second;
  44. length=arr[i][j];
  45. length++;
  46. stk.pop();
  47. //left
  48. if(j-1>=0 && arr[i][j-1]==length){
  49. stk.push({i,j-1});
  50. flag=1;
  51. }
  52. //right
  53. if(j+1<w && arr[i][j+1]==length){
  54. stk.push({i,j+1});
  55. flag=1;
  56. }
  57. //top
  58. if(i-1>=0 && arr[i-1][j]==length){
  59. stk.push({i-1,j});
  60. flag=1;
  61. }
  62. //down
  63. if(i+1<h && arr[i+1][j]==length){
  64. stk.push({i+1,j});
  65. flag=1;
  66. }
  67. //NW
  68. if((i-1>=0&&j-1>=0) && arr[i-1][j-1]==length){
  69. stk.push({i-1,j-1});
  70. flag=1;
  71. }
  72. //NE
  73. if((i-1>=0&&j+1<w) && arr[i-1][j+1]==length){
  74. stk.push({i-1,j+1});
  75. flag=1;
  76. }
  77. //SW
  78. if((i+1<h&&j-1>=0) && arr[i+1][j-1]==length){
  79. stk.push({i+1,j-1});
  80. flag=1;
  81. }
  82. //SE
  83. if((i+1<h&&j+1<w) && arr[i+1][j+1]==length){
  84. stk.push({i+1,j+1});
  85. flag=1;
  86. }
  87. if(flag==0){
  88. if(length-1>ans)
  89. ans=length-1;
  90. }
  91. }
  92. return ans;
  93. }
  94.  
  95.  
  96.  
Success #stdin #stdout 0s 4476KB
stdin
4 3
ABE
CFG
BDH
ABC
0 0
stdout
Case 1: 4