NKMINES - Trò chơi dò mìn

Tác giả: ladpro98

Ngôn ngữ: Pascal

program nkmines;
uses    math;
const   fi='';
        maxn=222;
        dx:array[1..8] of longint = (-1,-1,-1,0,0,1,1,1);
        dy:array[1..8] of longint = (-1,0,1,-1,1,-1,0,1);
var     a,p:array[1..maxn,1..maxn] of longint;
        m,n:longint;

procedure input;
var     inp:text;
        i,j:longint;
begin
        assign(inp,fi);reset(inp);
        readln(inp,m,n);
        for i:=1 to m do
        begin
                for j:=1 to n do read(inp,a[i,j]);
                readln(inp);
        end;
        close(inp);
end;

function test(i,j,q:longint):boolean;
var     x,y,k,t:longint;
begin
        t:=0;
        for k:=1 to 8 do
        begin
                x:=i+dx[k];y:=j+dy[k];
                if (1<=x) and (x<=m) and (1<=y) and (y<=n)
                and (p[x,y]=1) then inc(t);
        end;
        if t>a[i,j] then exit(false);
        if q=1 then if t=a[i,j] then exit(true) else exit(false);
        if q=2 then if (t>=a[i,j]-1) then exit(true) else exit(false);
        if q=3 then if (t>=a[i,j]-3) then exit(true) else exit(false);
        if q=4 then if (t>=a[i,j]-2) then exit(true) else exit(false);
        if q=5 then if (t>=a[i,j]-5) then exit(true) else exit(false);
        if q=6 then if (t>=a[i,j]-4) then exit(true) else exit(false);
        if q=7 then if (t>=a[i,j]-6) then exit(true) else exit(false);
        if q=8 then if (t>=a[i,j]-7) then exit(true) else exit(false);
end;

procedure output;
var     i,j:longint;
begin
        for i:=1 to m do
        begin
                for j:=1 to n do write(p[i,j],' ');
                writeln;
        end;
end;

procedure back(i,j,sx,sy:longint);
var     k,x,y,v:longint;
        t:boolean;
begin
        if i>m then
        begin
                output;
                halt;
        end;
        for v:=0 to 1 do
        begin
                p[i,j]:=v;
                t:=true;
                for k:=1 to 8 do
                begin
                        x:=i+dx[k]; y:=j+dy[k];
                        if (1<=x) and (x<=m) and (1<=y) and (y<=n) then
                        t:=test(x,y,k);
                        if not t then break;
                end;
                if t then
                begin
                        x:=i+1;y:=j-1;
                        if (1<=x) and (x<=m) and (1<=y) and (y<=n) then back(x,y,sx,sy)
                        else
                        begin
                                if (sx=1) then
                                        if sy<n then back(sx,sy+1,sx,sy+1)
                                        else    back(sx+1,sy,sx+1,sy)
                                else
                                        back(sx+1,sy,sx+1,sy);
                        end;
                end;
         end;
        p[i,j]:=0;
end;

begin
        input;
        back(1,1,1,1);
end.

Download