{
  CTU Open Contest 2002
  =====================
  Sample solution for the problem: cast

  Martin Kacer, Oct 2002
}

Program Dice;

Const
	MAXSIZE = 512;
	MAXPTS = 6;
	chPts = 'X';
	chDie = '*';
	chBkg = '.';

Type
	TQueue = Array [1..MAXSIZE*MAXSIZE] of Integer;

Var DieX, DieY : TQueue;
	DieB, DieE : Integer;
	PtsX, PtsY : TQueue;
	PtsB, PtsE : Integer;
	SizeX, SizeY : Integer;
	Field : Array [1..MAXSIZE, 1..MAXSIZE] of Char;
	NumCount : Array [1..MAXPTS] of Integer;


{enqueue the given point pixel if it is a point pixel}
Procedure PtsEnqueue (X, Y: Integer);
Begin
	If (Field[X,Y] = chPts) then
	Begin
		PtsX[PtsE] := X;
		PtsY[PtsE] := Y;
		Field[X,Y] := chDie;
		Inc (PtsE);
	End;
End; { PtsEnqueue }


{fill the point, make a die from it}
Procedure PtsFill (X, Y: Integer);
Begin
	PtsB := 1; PtsE := 1;
	PtsEnqueue (X, Y);
	While (PtsB < PtsE) do
	Begin
		X := PtsX[PtsB];
		Y := PtsY[PtsB];
		Inc (PtsB);
		If (X > 1) then PtsEnqueue (X-1, Y);
		If (X < SizeX) then PtsEnqueue (X+1, Y);
		If (Y > 1) then PtsEnqueue (X, Y-1);
		If (Y < SizeY) then PtsEnqueue (X, Y+1);
	End;
End; { PtsFill }


{enqueue the die pixel;
if it is a point, turn it into die and increment the parameter}
Procedure DieEnqueue (X, Y: Integer; Var Cnt: Integer);
Begin
	If (Field[X,Y] = chPts) then
	Begin
		PtsFill (X, Y);
		Inc (Cnt);
	End;

	If (Field[X,Y] = chDie) then
	Begin
		DieX[DieE] := X;
		DieY[DieE] := Y;
		Field[X,Y] := chBkg;
		Inc (DieE);
	End;
End; { DieEnqueue }


{erase one die and count its points during that}
Function DieFill (X, Y: Integer) : Integer;
Var Cnt: Integer;
Begin
	Cnt := 0;
	DieB := 1; DieE := 1;
	DieEnqueue (X, Y, Cnt);
	While (DieB < DieE) do
	Begin
		X := DieX[DieB];
		Y := DieY[DieB];
		Inc (DieB);
		If (X > 1) then DieEnqueue (X-1, Y, Cnt);
		If (X < SizeX) then DieEnqueue (X+1, Y, Cnt);
		If (Y > 1) then DieEnqueue (X, Y-1, Cnt);
		If (Y < SizeY) then DieEnqueue (X, Y+1, Cnt);
	End;
	DieFill := Cnt;
End; { DieFill }


{read the situation}
Procedure ReadView;
Var X, Y: Integer;
Begin
	For X := 1 to SizeX do
	Begin
		For Y := 1 to SizeY do
			Read (Field[X,Y]);
		ReadLn;
	End;
End;


{find all dice and count points on them}
Procedure CountDice;
Var X, Y, C: Integer;
Begin
	For X := 1 to MAXPTS do NumCount[X] := 0;
	For X := 1 to SizeX do
		For Y := 1 to SizeY do
			If (Field[X,Y] <> chBkg) then
			Begin
				C := DieFill (X, Y);
				If (C < 1) or (C > MAXPTS) then
					WriteLn ('!!!!!!!!! ', C)
				else
					Inc (NumCount[C]);
			End;
End;


Var I, J: Integer;

Begin
	Repeat
		ReadLn (SizeX, SizeY);
		If (SizeX > 0) then
		Begin
			ReadView;
			CountDice;
			Write('Throw:');
			For I := 1 to MAXPTS do
				If NumCount[I] > 0 then
					For J := 1 to NumCount[I] do
						Write (' ', I);
			WriteLn;
		End;
	until (SizeX = 0);
End.

