其实这道题目还是有点难度的,趋于对bfs的信心,还是勇敢地用bfs码。
这题特判的地方比较wei详情看代码注释。
因为要保留最优解在一张二维表,所以时间并不会太短。效率不高
代码:
const z:array[1..4,1..2]of -1..1=((-1,0),(0,-1),(1,0),(0,1));//四个方向
var i,j,k:longint;
a:array[0..101,0..101]of longint;
b:array[0..101,0..101]of longint;
x,y,u,p,q:array[0..10001]of longint;
boo:array[0..10001]of boolean;
h,t,m,n:longint;
function pd(m,n:longint):longint;//判断要用几元钱
begin
if n=2 then exit(2);
if m=n then exit(0);
exit(1);
end;
function pd2(m,n:longint):longint;//判断颜色是否变换
begin
if n=2 then exit(m);
exit(n);
end;
begin
read(n,m);
for i:=1 to n do
for j:=1 to n do
begin
a[i,j]:=2;//无色
b[i,j]:=maxlongint;//初值
end;
b[1,1]:=0;
for i:=1 to m do
begin
read(h,t,k);
a[h,t]:=k;
end;
h:=1;
t:=1;
b[1,1]:=0;//1,1自然为零
x[1]:=1;
y[1]:=1;
boo[1]:=false;
p[1]:=a[1,1];//记录颜色
q[1]:=0;
repeat
for i:=1 to 4 do
if b[x[t]+z[i,1],y[t]+z[i,2]]>q[t]+pd(p[t],a[x[t]+z[i,1],y[t]+z[i,2]]) then//保证当前解比原解小
begin
if (not boo[t]) or (a[x[t]+z[i,1],y[t]+z[i,2]]<>2) then//如果要换颜色可不可以
begin
b[x[t]+z[i,1],y[t]+z[i,2]]:=q[t]+pd(p[t],a[x[t]+z[i,1],y[t]+z[i,2]]);//记录
inc(h);
if a[x[t]+z[i,1],y[t]+z[i,2]]=2 then boo[h]:=true;//如果换色了,则下次不可以换色了
p[h]:=pd2(p[t],a[x[t]+z[i,1],y[t]+z[i,2]]);//颜色记录
x[h]:=x[t]+z[i,1];
y[h]:=y[t]+z[i,2];
q[h]:=b[x[h],y[h]];
end;
end;
inc(t);
until t>h;
if b[n,n]=maxlongint then write(-1) else//是否有解
writeln(b[n,n]);//有解则输出
end.