电子老鼠闯迷宫pascal解题程序
生活随笔
收集整理的這篇文章主要介紹了
电子老鼠闯迷宫pascal解题程序
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
這題我是用廣度優(yōu)先搜索的方法來寫的
head是頭指針,tail是尾指針
我先找出下一個點,再判斷這個點能不能走,能走就記錄該點,到達終點時,就輸出。
我是用遞歸的方法輸出的
const
maxn=12;wayn=4;
dx:array[1..wayn]of longint=(-1,0,1,0);
dy:array[1..wayn]of longint=(0,1,0,-1);
var
px,py,qx,qy,s,last:longint;
a:array[0..maxn+1,0..maxn+1]of longint;
father:array[1..maxn*maxn]of longint;
state:array[1..maxn*maxn,1..2]of longint;
procedure init;
var
i,j,n:longint;
begin
? ? readln(n);
? ? readln(px,py,qx,qy);
? ? for i:=1 to n do
? ? begin
? ? ? ? for j:=1 to n do
? ? ? ? read(a[i,j]);
? ? ? ? readln;
? ? end;
end;
function check(x,y:integer):boolean;
begin
? ? check:=true;
? ? if (x<1)or(x>12)or(y<1)or(y>12) then check:=false;
? ? if a[x,y]=1 then check:=false;
end;
procedure print(x:longint);
begin
? ? if x=0 then exit;
? ? inc(s);
? ? print(father[x]);
? ? if x<>last then write('(',state[x,1],',',state[x,2],')->') else
? ? writeln('(',state[x,1],',',state[x,2],')');
end;
procedure bfs;
var
tail,head,k,i:integer;
begin
? ? head:=0;tail:=1;state[1,1]:=px;state[1,2]:=py;
? ? father[1]:=0;
? ? repeat
? ? ? ? ?inc(head);
? ? ? ? ?for k:=1 to wayn do
? ? ? ? ?if check(state[head,1]+dx[k],state[head,2]+dy[k]) then
? ? ? ? ?begin
? ? ? ? ? ? ?inc(tail);
? ? ? ? ? ? ?father[tail]:=head;
? ? ? ? ? ? ?state[tail,1]:=state[head,1]+dx[k];
? ? ? ? ? ? ?state[tail,2]:=state[head,2]+dy[k];
? ? ? ? ? ? ?a[state[tail,1],state[tail,2]]:=1;
? ? ? ? ? ? ?if (state[tail,1]=qx)and(state[tail,2]=qy) then
? ? ? ? ? ? ?begin
? ? ? ? ? ? ? ? ?s:=0;
? ? ? ? ? ? ? ? ?last:=tail;
? ? ? ? ? ? ? ? ?print(tail);
? ? ? ? ? ? ? ? ?writeln(s);
? ? ? ? ? ? ? ? ?tail:=0;
? ? ? ? ? ? ?end;
? ? ? ? ?end;
? ? until head>=tail;
end;
begin
? ? init;
? ? bfs;
end.
這題是我第一次用廣度優(yōu)先搜索的方法來寫程序,希望我能把廣度優(yōu)先搜索學(xué)會。
轉(zhuǎn)載于:https://www.cnblogs.com/YYC-0304/p/9500248.html
總結(jié)
以上是生活随笔為你收集整理的电子老鼠闯迷宫pascal解题程序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 未完成作业
- 下一篇: 骑士旅行pascal解题程序