How to generate an n x n matrix filled with elements from 1 to N^2 in spiral order in Pascal

1 Answer

0 votes
program SpiralMatrix;

uses crt;

procedure GenerateSpiralMatrix(n: Integer);
var
  matrix: array of array of Integer;
  top, bottom, left, right, value, i: Integer;
begin
  // Initialize the matrix
  SetLength(matrix, n, n);
  
  top := 0;
  bottom := n - 1;
  left := 0;
  right := n - 1;
  value := 1;

  // Fill the matrix in spiral order
  while (top <= bottom) and (left <= right) do
  begin
    // Fill top row
    for i := left to right do
    begin
      matrix[top][i] := value;
      Inc(value);
    end;
    Inc(top);

    // Fill right column
    for i := top to bottom do
    begin
      matrix[i][right] := value;
      Inc(value);
    end;
    Dec(right);

    // Fill bottom row
    if top <= bottom then
    begin
      for i := right downto left do
      begin
        matrix[bottom][i] := value;
        Inc(value);
      end;
      Dec(bottom);
    end;

    // Fill left column
    if left <= right then
    begin
      for i := bottom downto top do
      begin
        matrix[i][left] := value;
        Inc(value);
      end;
      Inc(left);
    end;
  end;

  // Print the matrix
  for i := 0 to n - 1 do
  begin
    for value := 0 to n - 1 do
      Write(matrix[i][value]:4);
    Writeln;
  end;
end;

var
  n: Integer;
begin
  n := 3; // size of the matrix
  if n > 0 then
    GenerateSpiralMatrix(n)
  else
    WriteLn('Matrix size must be greater than 0.');
end.



(*
run:

   1   2   3
   8   9   4
   7   6   5
 
*)

 



answered Jun 24, 2025 by avibootz
edited Jun 24, 2025 by avibootz
...