算法:搜索
其实就是求树的最长链。
1.先找一个是景点的地方。
2.以这个点为起点做一遍搜索,搜出一个最远点。
3.再以那个最远点做起点再搜一遍即可。
其实就是求树的最长链。
1.先找一个是景点的地方。
2.以这个点为起点做一遍搜索,搜出一个最远点。
3.再以那个最远点做起点再搜一遍即可。
做两遍搜索的原因是第一次搜索有可能不在最远点的位置上,因此还要根据这个点找一个最远的点,即直径。
program vijos1107;
const
maxn=1000;
dx:array [1..4] of -1..1=(0,-1,0,1);
dy:array [1..4] of -1..1=(-1,0,1,0);
var
n,m,tot,ans,mx,my:longint;
a:array [0..maxn,0..maxn] of char;
b:array [0..maxn,0..maxn] of boolean;
procedure init;
var
i,j:longint;
begin
readln(m,n);
fillchar(b,sizeof(b),false);
for i:=1 to n do
begin
for j:=1 to m do read(a[i,j]);
readln;
end;
end;
procedure dfs(x,y:longint);
var
i,tx,ty:longint;
begin
if tot>=ans then
begin
ans:=tot;
mx:=x;
my:=y;
end;
for i:=1 to 4 do
begin
tx:=x+dx[i];
ty:=y+dy[i];
if (tx>0) and (tx<=n) and (ty>0) and (ty<=m) and (a[tx,ty]='.') and (not b[tx,ty]) then
begin
b[tx,ty]:=true;
inc(tot);
dfs(tx,ty);
dec(tot);
end;
end;
end;
procedure main;
var
i,j:longint;
begin
for i:=1 to n do
begin
for j:=1 to m do
begin
if a[i,j]='.' then
begin
tot:=0;
b[i,j]:=true;
dfs(i,j);
fillchar(b,sizeof(b),false);
tot:=0;
b[mx,my]:=true;
dfs(mx,my);
writeln(ans);
close(input);
close(output);
halt;
end;
end;
end;
end;
begin
assign(input,'VJ1107.in'); reset(input);
assign(output,'VJ1107.out'); rewrite(output);
init;
main;
close(input); close(output);
end.
本文介绍了使用搜索算法求解树结构中最长路径的方法,包括寻找起点、进行两次深度优先搜索以确保找到直径,适用于图论和算法领域的学习。
665

被折叠的 条评论
为什么被折叠?



