这里给一个递归的程序,可以求任意两点间的最短路径,结果把最短距离以及中间的路径都显示出来。
给分吧,呵呵!
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
const Map:array[1..12,1..2] of integer
=((1,3),
(1,4),
(2,3),
(2,6),
(3,1),
(3,2),
(3,5),
(3,6),
(4,1),
(5,3),
(6,2),
(6,3));
var StepNowArr:array[1..6] of integer;
StepOutArr:array[1..6] of integer;
StepOut:integer;
StepMin:integer;
//递归搜索指定来源到指定目标的最短路径
proceduredo
Search(FromIndex, ToIndex, iStep:integer);
var i,j:integer;
begin
if (FromIndex=ToIndex) and (iStep<StepMin) then
begin
//到达目标,并且当前路径小于所记录的最短路径,则记录本次路径
StepMin:=iStep;
for j:=1 to StepMindo
StepOutArr[j]:=StepNowArr[j];
exit;
end;
if (iStep>=StepMin) or (iStep>=5) then
exit;
for i:=1 to 12do
if (FromIndex=Map[i,1]) and //所选路径的来源正是当前节点
(iStep+1<StepMin) then
//如果继续走还小于当前最短路径
begin
StepNowArr[iStep+1]:=Map[i,2];
//记录当前节点的目标
do
Search(Map[i,2],ToIndex,iStep+1);
//则递归继续搜索
end;
end;
//输出结果
proceduredo
Result(FromIndex, ToIndex:integer);
var i:integer;
s:string;
begin
s:=IntToStr(FromIndex);
for i:=1 to StepMindo
s:=s+'-->'+IntToStr(StepOutArr);
s:=s+' : '+IntToStr(StepMin);
showmessage(s);
end;
begin
//1--1
StepMin:=999;
do
Search(1,1,0);
do
Result(1,1);
//2--1
StepMin:=999;
do
Search(2,1,0);
do
Result(2,1);
//3--1
StepMin:=999;
do
Search(3,1,0);
do
Result(3,1);
//4--1
StepMin:=999;
do
Search(4,1,0);
do
Result(4,1);
//5--1
StepMin:=999;
do
Search(5,1,0);
do
Result(5,1);
//6--1
StepMin:=999;
do
Search(6,1,0);
do
Result(6,1);
end;
end.