application introduction to algorithms

Upload: truc-khuyen-duong-dang

Post on 07-Apr-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Application Introduction to Algorithms

    1/4

    BFSMin 0 l tp hp cc s 0 c chung cnh. Hy vit chng trnh m cc min 0.Input: File loang.inp, trong

    Dng u tin cho bit s dng m, s ct n M dng tip theo biu din bng vung gm cc s 0 hoc 1

    Output: File loang.out, trong Gm mt dng duy nht cha s k cho bit s min 0

    Loang.inp Loang.out4 70 0 1 0 1 1 00 0 1 1 1 0 00 0 0 0 0 0 00 0 0 0 0 0 0

    2

    Constdx:array[1..4] of shortint=(-1,0,1,0);dy:array[1..4] of shortint=(0,-1,0,1);

    Procedure BFS(i,j:integer); {LOANG chieu rong}Begin

    Fillchar(d,sizeof(d),inf);Fillchar(p,sizeof(p),-1);color:=a; {To mau nhung dinh co gia tri 1}color[i,j]:=1;d[i,j]:=0;p[i,j]:=-1;head:=1; tail:=1;qx[head]:=i;qy[head]:=j;

    while (head

  • 8/3/2019 Application Introduction to Algorithms

    2/4

    End;End;{---------------------------------------------CI TIN-------------------------------------}Procedure BFS(i,j:integer);Begin

    Fillchar(color,sizeof(color),0);Fillchar(d,sizeof(d),inf);Fillchar(p,sizeof(p),-1);color:=a; {To mau nhung dinh co gia tri 1}color[i,j]:=1;d[i,j]:=0;p[i,j]:=-1;head:=1; tail:=1;qx[head]:=i;qy[head]:=j;while (head

  • 8/3/2019 Application Introduction to Algorithms

    3/4

    Writeln(x2-k, y2-k);End;

    End;

    DFS

    Constdx:array[1..4] of shortint=(-1,0,1,0);dy:array[1..4] of shortint=(0,-1,0,1);

    Procedure MainDFS;Begin

    Fillchar(color, sizeof(color),0);Fillchar(p, sizeof(p),-1);time:=0;For i:=1 to m do

    For j:=1 to n doIf color[i,j]=0 then

    DFS(i,j);End;Procedure DFS(i,j:integer); {LOANG theo chieu sau}Var k:integer;Begin

    color[i,j]:=1; {da tham, gray}S:=S+1;{time:=time+1;d[i,j]:=time;}For k:=1 to 4 do {Xet cac dinh}

    if a[i+dx[k],j+dy[k]]=0 then {ke voi (i,j), co gia tri 0}if color[i+dx[k],j+dy[k]]=0 then {chua tham, white}Begin

    color[i+dx[k],j+dy[k]]:=1; {da tham, gray}p[i+dx[k],j+dy[k]]:=k; {luu parent}DFS(i+dx[k],j+dy[k]);

    End;color[i,j]:=2; {ket thuc, black}{time:=time+1;f[i,j]:=time;}

    End;Procedure MainDFS;Var i,j:integer;

    temp:integer;Begin

    Assign(fo, fileout);Rewrite(fo);For i:=1 to maxR do

  • 8/3/2019 Application Introduction to Algorithms

    4/4

    For j:=1 to maxC dop[i,j]:=-1;

    color:=a; {To mau truoc cac dinh co gia tri 1}dem:=0;For i:=1 to maxR do

    For j:=1 to maxC doif (color[i,j]=0) then {chua tham, white}Begindem:=dem+1;DFS(i,j);End;

    Writeln(fo,dem); {Dem so MIEN LIEN THONG}End;