program SpiralMatrix;
type
TMatrix = array[0..3, 0..3] of Integer;
procedure PrintMatrixInSpiralForm(matrix: TMatrix);
var
top, bottom, left, right, i: Integer;
begin
if Length(matrix) = 0 then Exit;
top := 0;
bottom := High(matrix);
left := 0;
right := High(matrix[0]);
while True do
begin
if left > right then Break;
// Top row
for i := left to right do
Write(matrix[top][i], ' ');
Writeln;
Inc(top);
if top > bottom then Break;
// Right column
for i := top to bottom do
Write(matrix[i][right], ' ');
Writeln;
Dec(right);
if left > right then Break;
// Bottom row
for i := right downto left do
Write(matrix[bottom][i], ' ');
Writeln;
Dec(bottom);
if top > bottom then Break;
// Left column
for i := bottom downto top do
Write(matrix[i][left], ' ');
Writeln;
Inc(left);
end;
end;
var
// Define the matrix
Matrix: TMatrix = (
(1, 2, 3, 4),
(5, 6, 7, 8),
(9, 10, 11, 12),
(13, 14, 15, 16)
);
begin
// Print the matrix in spiral order
PrintMatrixInSpiralForm(Matrix);
end.
(*
run:
1 2 3 4
8 12 16
15 14 13
9 5
6 7
11
10
*)