麻将游戏

Description

  在一种”麻将”游戏中,游戏是在一个有W*H格子的矩形平板上进行的。每个格子可以放置一个麻将牌,也可以不放(如图所示)。玩家的目标是将平板上的所有可通过一条路径相连的两张相同的麻将牌,从平板上移去。最后如果能将所有牌移出平板,则算过关。
  这个游戏中的一个关键问题是:两张牌之间是否可以被一条路径所连接,该路径满足以下两个特性:
  1. 它由若干条线段组成,每条线段要么是水平方向,要么是垂直方向。
  2. 这条路径不能横穿任何一个麻将牌 (但允许路径暂时离开平板)。
  这是一个例子:

这里写图片描述

  在(1,3)的牌和在(4, 4)的牌可以被连接。(2, 3)和(3, 4)不能被连接。
  你的任务是编一个程序,检测两张牌是否能被一条符合以上规定的路径所连接。

Input

  输入文件的第一行有两个整数w,h (1<=w,h<=75),表示平板的宽和高。接下来h行描述平板信息,每行包含w个字符,如果某格子有一张牌,则这个格子上有个’X’,否则是一个空格。平板上最左上角格子的坐标为(1,1),最右下角格子的坐标为(w,h)。接下来的若干行,每行有四个数x1, y1, x2, y2 ,且满足1<=x1,x2<=w,1<=y1,y2<=h,表示两张牌的坐标(这两张牌的坐标总是不同的)。如果出现连续四个0,则表示输入结束。

Output

  输出文件中,对于每一对牌输出占一行,为连接这一对牌的路径最少包含的线段数。如果不存在路径则输出0。

Sample Input

5 4
XXXXX
X X
XXX X
XXX
2 3 5 3
1 3 4 4
2 3 3 4
0 0 0 0

Sample Output

4
3
0

分析
用广搜来做
每一次向四个方向搜(上、下、左、右)一直搜到有麻将挡住为止。(ps:麻将的路线可以走到棋盘外面)

程序:

const
dx:array[1..4]of longint=(0,1,0,-1);
dy:array[1..4]of longint=(1,0,-1,0);

var
i,j,head,tail,n,m,qx,qy,px,py:longint;
state:array[-1..10000,1..2]of longint;
father:array[-1..100,-1..100]of longint;
f:array[-1..10000]of integer;
a:array[-1..100,-1..100]of char;
bz:boolean;

function pd(x,y:longint):boolean;
begin
    pd:=not(true);
    if (x>m+1)or(x<0)or(y>n+1)or(y<0) then exit;
    if a[x,y]='X' then exit;
    if f[head]+1<=f[father[x,y]] then pd:=true;
end;

procedure try(x,y:longint);
begin
    inc(tail);
    state[tail,1]:=dx[x]*y+state[head,1];
    state[tail,2]:=dy[x]*y+state[head,2];
    father[state[tail,1],state[tail,2]]:=tail;
    f[tail]:=f[head]+1;
    if (state[tail,1]=qx)and(state[tail,2]=qy) then
    begin
        writeln(f[tail]);
        head:=0;
        exit;
    end;
    if not(pd(state[tail,1]+dx[x],state[tail,2]+dy[x])) then exit;
    try(x,y+1);
end;

procedure bfs;
var
i:longint;
begin
    head:=0; tail:=1;
    state[1,1]:=px; state[1,2]:=py; f[1]:=0; father[px,py]:=1;
    repeat
         inc(head);
         for i:=1 to 4 do
         if pd(state[head,1]+dx[i],state[head,2]+dy[i]) then
         begin
             try(i,1);
             if head=0 then exit;
         end;
    until head>=tail;
    writeln(0);
end;

begin
    readln(n,m);
    for i:=1 to m do
    begin
        for j:=1 to n do
        read(a[i,j]);
        readln;
    end;
    bz:=true;
    while bz=true do
    begin
        fillchar(f,sizeof(f),$7f div 2);
        readln(py,px,qy,qx);
        if (px=0)and(0=py)and(0=qx)and(0=qy) then break;
        a[qx,qy]:=' ';
        bfs;
        a[qx,qy]:='X';
        fillchar(state,sizeof(state),#0);
        fillchar(father,sizeof(father),#0);
    end;
end.

原文地址:https://www.cnblogs.com/YYC-0304/p/9500057.html