trim method

Matrix trim()

Trims the matrix by removing empty rows and columns from all sides.

This method removes rows and columns that contain only false values from the edges of the matrix, effectively trimming it to the smallest possible size that contains all true values.

Returns: A new Matrix object that is a trimmed version of the original. If the original matrix is empty or contains only false values, it returns an empty Matrix.

Note: This method does not modify the original matrix but returns a new one.

Implementation

Matrix trim() {
  if (isEmpty || isEmpty) {
    return Matrix();
  }
  // Find the boundaries of the content
  int topRow = 0;
  int bottomRow = rows - 1;
  int leftCol = 0;
  int rightCol = cols - 1;

  // Find top row with content
  while (topRow < rows && !_data[topRow].contains(true)) {
    topRow++;
  }

  // Find bottom row with content
  while (bottomRow > topRow && !_data[bottomRow].contains(true)) {
    bottomRow--;
  }

  // Find left column with content
  outer:
  while (leftCol < cols) {
    for (int i = topRow; i <= bottomRow; i++) {
      if (_data[i][leftCol]) {
        break outer;
      }
    }
    leftCol++;
  }

  // Find right column with content
  outer:
  while (rightCol > leftCol) {
    for (int i = topRow; i <= bottomRow; i++) {
      if (_data[i][rightCol]) {
        break outer;
      }
    }
    rightCol--;
  }

  // Crop the grid
  return Matrix.fromBoolMatrix(
    List.generate(
      bottomRow - topRow + 1,
      (i) => _data[i + topRow].sublist(leftCol, rightCol + 1),
    ),
  );
}