fork download
  1. #include <iostream>
  2. #include <cstring>
  3. #include <stack>
  4. #define maxn 1000
  5. using namespace std;
  6. stack <int> s;
  7. char g[maxn][maxn];
  8. bool used[maxn][maxn];
  9. int n,m, max_d=0, root_x=0, root_y=0;
  10. void dfs(int cx,int cy, int h){
  11. s.push(cx);
  12. s.push(cy);
  13. s.push(h);
  14. while(!s.empty()){
  15. int h=s.top();
  16. s.pop();
  17. int y=s.top();
  18. s.pop();
  19. int x=s.top();
  20. s.pop();
  21. used[x][y]=true;
  22. if(h>max_d)
  23. max_d=h,root_x=x,root_y=y;
  24. if(x>0 && g[x-1][y]=='.' && !used[x-1][y])
  25. s.push(x-1),s.push(y),s.push(h+1);
  26. if(y>0 && g[x][y-1]=='.' && !used[x][y-1])
  27. s.push(x),s.push(y-1),s.push(h+1);
  28. if(x<n-1 && g[x+1][y]=='.' && !used[x+1][y])
  29. s.push(x+1),s.push(y),s.push(h+1);
  30. if(y<m-1 && g[x][y+1]=='.' && !used[x][y+1])
  31. s.push(x),s.push(y+1),s.push(h+1);
  32. }
  33. }
  34. int main(){
  35. cin>>m>>n;
  36. for(int i=0; i<n; ++i){
  37. cin>>g[i];
  38. for(int j=0; j<m; ++j)
  39. used[i][j]=false;
  40. }
  41. for(int i=0; i<n; ++i){
  42. for(int j=0; j<m; ++j)
  43. if(g[i][j]=='.' && !used[i][j]){
  44. dfs(i,j,0);
  45. for(int k=0;k<n;++k)
  46. for(int l=0;l<m;++l)
  47. used[k][l]=0;
  48. dfs(root_x,root_y,0);
  49. }
  50. }
  51. cout<<max_d<<endl;
  52. return 0;
  53. }
Success #stdin #stdout 0s 18016KB
stdin
3 3
#.#
...
#.#
stdout
2