pascal问题,请用深度优先搜索解决
pascal问题,请用深度优先搜索解决你能确定出一条从A到B的路线,使这条路线所经过的数字之和正好等于50.请编程序解决这个问题。(A、B两点用0表示)12341A---...
pascal问题,请用深度优先搜索解决
你能确定出一条从A到B的路线,使这条路线所经过的数字之和正好等于50.请编程序解决这个问题。(A、B两点用0表示)
1 2 3 4
1 A---4---7---3
| | | |
2 1---5---2---6
| | | |
3 3---2---5---4
| | | |
4 1---6---7---b
图有问题啊,应该是这样的:
  1    2    3    4
1 A---4---7---3
    |    |     |      |
2 1---5---2---6
    |    |     |       |
3 3---2---5---4
    |    |     |      |
4 1---6---7---b 展开
你能确定出一条从A到B的路线,使这条路线所经过的数字之和正好等于50.请编程序解决这个问题。(A、B两点用0表示)
1 2 3 4
1 A---4---7---3
| | | |
2 1---5---2---6
| | | |
3 3---2---5---4
| | | |
4 1---6---7---b
图有问题啊,应该是这样的:
  1    2    3    4
1 A---4---7---3
    |    |     |      |
2 1---5---2---6
    |    |     |       |
3 3---2---5---4
    |    |     |      |
4 1---6---7---b 展开
2个回答
展开全部
基本深度优先搜索;直接贴标程.
var
a:array[1..10,1..10]of char;
f:array[1..10,1..10,1..2] of integer;
m,n,i,j,cx,cy,mx,my:integer;
procedure print(x,y:integer);
var
i,j:integer;
begin
if (x=cx) and (y=cy) then begin writeln(cx,cy);halt;end;
writeln(x,y);
print(f[x,y,1],f[x,y,2]);
end;
procedure try(x,y,z:integer);
begin
if z>50 then exit;
if (x=mx) and (y=my) then
begin
if z=50 then begin print(x,y);halt;end;
exit;
end.
if x<m-1 then
begin
f[x+1,y,1]:=x;f[x+1,y,2]:=y;
try(x+1,y,z+val(a[x+1,y]));
end;
if y<n-1 then
begin
f[x,y+1,1]:=x;f[x,y+1,2]:=y;
try(x,y+1,z+val(a[x,y+1]));
end;
if x>1 then
begin
f[x+1,y,1]:=x;f[x+1,y,2]:=y;
try(x-1,y,z+val(a[x-1,y]));
end;
if y>1 then
begin
f[x+1,y,1]:=x;f[x+1,y,2]:=y;
try(x,y-1,z+val(a[x,y-1]));
end;
end;
begin
readln(m,n);
for i:=1 to m do
for j:=1 to n do
begin
read(a[i,j]);
if a[i,j]='A' then begin cx:=i;cy:=j;end;
if a[i,j]='B' then begin mx:=i;my:=j;end;
end;
try(cx,cy,0);
end.
var
a:array[1..10,1..10]of char;
f:array[1..10,1..10,1..2] of integer;
m,n,i,j,cx,cy,mx,my:integer;
procedure print(x,y:integer);
var
i,j:integer;
begin
if (x=cx) and (y=cy) then begin writeln(cx,cy);halt;end;
writeln(x,y);
print(f[x,y,1],f[x,y,2]);
end;
procedure try(x,y,z:integer);
begin
if z>50 then exit;
if (x=mx) and (y=my) then
begin
if z=50 then begin print(x,y);halt;end;
exit;
end.
if x<m-1 then
begin
f[x+1,y,1]:=x;f[x+1,y,2]:=y;
try(x+1,y,z+val(a[x+1,y]));
end;
if y<n-1 then
begin
f[x,y+1,1]:=x;f[x,y+1,2]:=y;
try(x,y+1,z+val(a[x,y+1]));
end;
if x>1 then
begin
f[x+1,y,1]:=x;f[x+1,y,2]:=y;
try(x-1,y,z+val(a[x-1,y]));
end;
if y>1 then
begin
f[x+1,y,1]:=x;f[x+1,y,2]:=y;
try(x,y-1,z+val(a[x,y-1]));
end;
end;
begin
readln(m,n);
for i:=1 to m do
for j:=1 to n do
begin
read(a[i,j]);
if a[i,j]='A' then begin cx:=i;cy:=j;end;
if a[i,j]='B' then begin mx:=i;my:=j;end;
end;
try(cx,cy,0);
end.
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询