5,392
社区成员
发帖
与我相关
我的任务
分享
广度优先搜索:
uses Classes;
TPixel =record //定义点类型
x,y:integer;
color: TColor;
end;
{Canvas为原图画布,pt为起始搜索点,返回一个与pt颜色相同的点的列表}
function (Canvas: TCanvas;pt:TPixel): TList;
const
direct :array [1..4,1..2] of shortint =((0,-1),(0,1),(-1,0),(1,0)); //方向增量
var
dl: array [1..10000] of TPixel; //队列
head,tail,i:Integer; //head为队首指针,tail为队尾指针
tmp,tmp2:TPixel;
begin
head:=0; tail:=1; FillChar(dl,sizeof(dl),0); dl[tail]:=pt; //初始化队列
result := TList.Create;
while head<>tail do
begin
Inc(head); //队首加1
tmp:=dl[head]; //出队
for i:= 1 to 4 do //遍历四个方向
begin
tmp2.X :=tmp.X+direct[i,1];
tmp2.Y :=tmp.Y+direct[i,2];
if (tmp2.X<0)or(tmp2.X>Canvas.Width)or(tmp2.Y<0)or(tmp2.Y>Canvas.Width) then
continue; //如果越界则跳过
tmp2.Color := Canvas.Pixels[tmp2.X,tmp2.Y];
if tmp2.Color = pt.Color then //如果颜色相同则入队,并加入结果中
begin
Inc(tail);
dl[tail]:=tmp2;
result.Add(@tmp2);
end;
end;
end;
end;