﻿(*********************
Biblioteka uždaviniui 'zadintuvas'

Kodavimas UTF-8

Vertinimo metu bus naudojama kita biblioteka.
**********************)

unit zadintuvas_bib;

interface

function gautiN(): integer;
function gautiM(): integer;
function yraBaldas(e, s: integer): boolean;
function atstumas(e, s: integer): integer;
procedure zadintuvas(e, s: integer);

implementation

const
	MAXN = 210;
	MAXCALL = 10;
	INFILE = 'zadintuvas.in';
	OUTFILE = 'zadintuvas.out';

var
	_N, _M: integer;
	_room: array[1..MAXN, 1..MAXN] of char;
	_out: text;
	_clock_e, _clock_s: integer;
	_cnt: integer;

procedure _error(err: string; code: integer);
begin
	writeln(_out, 'BLOGAI: ', err);
	close(_out);
	halt(code);
end;

procedure _read;
var
	fin: text;
	i: integer;
begin
	assign(fin, INFILE);
	reset(fin);
	readln(fin, _N, _M);
	readln(fin, _clock_e, _clock_s);
	for i := 1 to _N do
		readln(fin, _room[i]);
	close(fin);
	assign(_out, OUTFILE);
	rewrite(_out);
	if (_clock_e < 1) or (_clock_e > _N) or (_clock_s < 1) or (_clock_s > _M)
		then _error('Žadintuvas už kambario ribų', -1);
	if not yraBaldas(_clock_e, _clock_s)
		then _error('Zadintuvas ne po baldu', -1);
end;

function gautiN(): integer;
begin
	gautiN := _N;
end;

function gautiM(): integer;
begin
	gautiM := _M;
end;

function yraBaldas(e, s: integer): boolean;
begin
	if (e < 1) or (e > _N) or (s < 1) or (s > _M)
		then _error('Tikrinama už kambario ribų', 0);
	yraBaldas := _room[e][s] = '#';
end;

function atstumas(e, s: integer): integer;
var
	r: integer;
begin
	writeln(_out, '> atstumas(', e, ', ', s, ')');
	if _cnt >= MAXCALL
		then _error('Per daug kartų kviečiama funkcija atstumas()', 0);
	inc(_cnt);
	if (e < 1) or (e > _N) or (s < 1) or (s > _M)
		then _error('Koordinatės už kambario ribų', 0);
	if yraBaldas(e, s)
		then _error('Bandoma tikrinti po baldu', 0);
	r := abs(_clock_e - e) + abs(_clock_s - s);
	writeln(_out, '< ', r);
	atstumas := r;
end;

procedure zadintuvas(e, s: integer);
begin
	writeln(_out, '> zadintuvas(', e, ', ', s, ')');
	if (e < 1) or (e > _N) or (s < 1) or (s > _M)
		then _error('Koordinatės už kambario ribų', 0);
	if (e <> _clock_e) or (s <> _clock_s)
		then _error('Atsakymas neteisingas', 0);
	writeln(_out, 'GERAI');
	close(_out);
	halt(0);
end;

begin
	_cnt := 0;
	_read;
end.
