forked from apurvapriyadarshi/codeforces-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Diameterofatree(spoj).cpp
107 lines (106 loc) · 2.69 KB
/
Diameterofatree(spoj).cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include<iostream>
#include<stack>
#include<cstdio>
using namespace std;
#define MAX 10000
char matrix[MAX][MAX];
bool visited[MAX][MAX];
bool finalVisited[MAX][MAX];
//vector<pair<int , int>>graph[MAX];
int c , r;
pair <int, pair <int , int > > DFS(int x , int y)
{
int max_height = 0;
pair<int , int> ans;
stack <pair <int , int> >S;
visited[x][y] = true;
S.push(make_pair(x , y));
bool flag = false;
while(!S.empty())
{
x = S.top().first;
y = S.top().second;
flag = false;
if((y+1) < c && !visited[x][y+1] && matrix[x][y+1] == '.')
{
S.push(make_pair(x , y+1));
visited[x][y+1] = true;
flag = true;
}
else if((x + 1) < r && !visited[x+1][y] && matrix[x+1][y] == '.')
{
S.push(make_pair(x+1 , y));
visited[x+1][y] = true;
flag = true;
}
else if(y > 0 && !visited[x][y-1] && matrix[x][y-1] && matrix[x][y-1] == '.')
{
S.push(make_pair(x , y - 1));
visited[x][y-1] = true;
flag = true;
}
else if(x > 0 && !visited[x-1][y] && matrix[x-1][y] && matrix[x-1][y] == '.')
{
S.push(make_pair(x - 1 , y));
visited[x-1][y] = true;
flag = true;
}
if(S.size() > max_height)
{
max_height = S.size();
ans = S.top();
}
if(!flag)
S.pop();
}
return make_pair(max_height , ans);
}
int findDiameter(int x , int y)
{
pair<int , pair<int , int> > leaf = DFS(x,y);
for(int i = 0 ; i < r ; i++)
{
for(int j = 0 ; j < c ; j++)
{
if(visited[i][j])
{
finalVisited[i][j] = true;
visited[i][j] = false;
}
}
}
return DFS(leaf.second.first , leaf.second.second).first;
}
int main()
{
int t;
cin >> t;
while(t--)
{
cin >> c >> r;
for(int i = 0 ; i < r ; i++)
{
for(int j = 0 ; j < c ; j++)
{
visited[i][j] = false;
finalVisited[i][j] = false;
}
}
for(int i = 0 ; i < r ; i++)
cin >> matrix[i];
int diameter = 0;
for(int i = 0 ; i < r ; i++)
{
for(int j = 0 ; j < c ; j++)
{
if(!finalVisited[i][j] && matrix[i][j] == '.')
{
//finalVisited[i][j] = true;
diameter = max(diameter , findDiameter(i , j) - 1);
}
}
}
cout << "Maximum rope length is " << diameter << "." << endl;
}
return 0;
}