影像之结构化特征(graph)

本文探讨了一道关于搜索算法的题目,强调了题目中横竖颠倒这一关键点,通过详细步骤阐述了如何正确解决该问题,并分享了优化思路。
算法:搜索

很简单的一道搜索题,唯一需要注意的是横竖是颠倒的,这一点需要特别注意,第一次做的时候错就错在这了。。

program graph;

const
 maxn=1000;
 maxzt=1000000;
 dx:array [1..4] of -1..1=(0,-1,0,1);
 dy:array [1..4] of -1..1=(-1,0,1,0);

type
 atp=record
  x,y,dep:longint;
 end;

var
 n,head,tail,tot:longint;
 ans:array [0..maxzt] of longint;
 a:array [0..maxn,0..maxn] of char;
 que:array [0..maxzt] of atp;

procedure init;
var
 i,j:longint;
begin
 readln(n);
 for i:=1 to n do
  begin
   for j:=1 to n do read(a[i,j]);
   readln;
  end;
end;

procedure bfs(x,y:longint);
var
 i,tx,ty:longint;
begin
 head:=0;
 tail:=1;
 que[1].x:=x;
 que[1].y:=y;
 que[1].dep:=1;
 a[x,y]:='0';
 while head<tail do
  begin
   inc(head);
   for i:=1 to 4 do
    begin
     tx:=que[head].x+dx[i];
     ty:=que[head].y+dy[i];
     if (tx>0) and (tx<=n) and (ty>0) and (ty<=n) and (a[tx,ty]='1') then
      begin
       a[tx,ty]:='0';
       inc(tail);
       que[tail].x:=tx;
       que[tail].y:=ty;
       que[tail].dep:=que[head].dep+1;
      end;
    end;
  end;
 inc(tot);
 ans[tot]:=que[tail].dep;
end;

procedure qsort(l,r:longint);
var
 i,j,m,t:longint;
begin
 i:=l;
 j:=r;
 m:=ans[(l+r) shr 1];
 repeat
  while ans[i]<m do inc(i);
  while ans[j]>m do dec(j);
  if i<=j then
   begin
    t:=ans[i];
    ans[i]:=ans[j];
    ans[j]:=t;
    inc(i);
    dec(j);
   end;
 until i>j;
 if i<r then qsort(i,r);
 if l<j then qsort(l,j);
end;

procedure main;
var
 i,j:longint;
begin
 for j:=1 to n do
  begin
   for i:=1 to n do
   if a[i,j]='1' then bfs(i,j);
  end;
 qsort(1,tot);
end;

procedure print;
var
 i:longint;
begin
 writeln(tot);
 for i:=1 to tot do writeln(ans[i]);
end;

begin
 assign(input,'graph.in'); reset(input);
 assign(output,'graph.out'); rewrite(output);

 init;
 main;
 print;

 close(input); close(output);
end.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值