How to change all elements of row i and column j in a binary matrix to 0 if cell[i, j] is 0 in Pascal

1 Answer

0 votes
program ChangeBinaryMatrixProgram;

const
  R = 5 - 1; // start from 0
  C = 6 - 1; // start from 0

type
  TMatrix = array[0..R, 0..C] of Integer;

procedure ChangeRowColumn(var matrix: TMatrix; row, col: Integer);
var
  i, j, rows, cols: Integer;
begin
  rows := Length(matrix);
  cols := Length(matrix[0]);

  for j := 0 to cols - 1 do
    if matrix[row][j] <> 0 then
      matrix[row][j] := -1;

  for i := 0 to rows - 1 do
    if matrix[i][col] <> 0 then
      matrix[i][col] := -1;
end;

procedure ChangeBinaryMatrix(var matrix: TMatrix);
var
  i, j, rows, cols: Integer;
begin
  rows := Length(matrix);
  if rows = 0 then Exit;
  cols := Length(matrix[0]);
  if cols = 0 then Exit;

  for i := 0 to rows - 1 do
    for j := 0 to cols - 1 do
      if matrix[i][j] = 0 then
        ChangeRowColumn(matrix, i, j);

  for i := 0 to rows - 1 do
    for j := 0 to cols - 1 do
      if matrix[i][j] = -1 then
        matrix[i][j] := 0;
end;

procedure PrintMatrix(const matrix: TMatrix);
var
  i, j, rows, cols: Integer;
begin
  rows := Length(matrix);
  cols := Length(matrix[0]);
  for i := 0 to rows - 1 do
  begin
    for j := 0 to cols - 1 do
      Write(matrix[i][j], ' ');
    Writeln;
  end;
end;

var
  matrix: TMatrix = (
    (1, 1, 0, 1, 1, 1),
    (1, 1, 1, 1, 1, 1),
    (1, 1, 0, 1, 1, 1),
    (1, 1, 1, 1, 1, 1),
    (1, 0, 1, 1, 1, 1)
  );
  
begin
  ChangeBinaryMatrix(matrix);
  
  PrintMatrix(matrix);
end.

  
  
(*
run:
 
0 0 0 0 0 0 
1 0 0 1 1 1 
0 0 0 0 0 0 
1 0 0 1 1 1 
0 0 0 0 0 0 
 
*)

 



answered Jul 5 by avibootz
...