program RotateMatrixLeft;
const
N = 3; // Size of the square matrix
type
TMatrix = array[1..N, 1..N] of Integer;
// Prints the matrix to the console
procedure PrintMatrix(matrix: TMatrix);
var
i, j: Integer;
begin
for i := 1 to N do
begin
for j := 1 to N do
Write(matrix[i, j], ' ');
Writeln;
end;
end;
// Rotates a square matrix 90 degrees to the left (counterclockwise)
// param matrix - The square matrix to rotate
procedure RotateMatrix90DegreesLeft(var matrix: TMatrix);
var
layer, i, offset: Integer;
first, last: Integer;
top: Integer;
begin
// Perform the rotation in-place
for layer := 1 to N div 2 do
begin
first := layer;
last := N - layer + 1;
for i := first to last - 1 do
begin
offset := i - first;
// Save the top element
top := matrix[first, i];
// Move right to top
matrix[first, i] := matrix[i, last];
// Move bottom to right
matrix[i, last] := matrix[last, last - offset];
// Move left to bottom
matrix[last, last - offset] := matrix[last - offset, first];
// Move top to left
matrix[last - offset, first] := top;
end;
end;
end;
var
matrix: TMatrix;
begin
// Initialize the matrix
matrix[1,1] := 1; matrix[1,2] := 2; matrix[1,3] := 3;
matrix[2,1] := 4; matrix[2,2] := 5; matrix[2,3] := 6;
matrix[3,1] := 7; matrix[3,2] := 8; matrix[3,3] := 9;
RotateMatrix90DegreesLeft(matrix);
Writeln('Matrix After 90 degrees Left Rotation:');
PrintMatrix(matrix);
end.
(*
run:
Matrix After 90 degrees Left Rotation:
3 6 9
2 5 8
1 4 7
*)