Skip to main content
2 of 3
deleted 122 characters in body
Mr. Xcoder
  • 42.5k
  • 9
  • 81
  • 214

Trim that distracting background off!

Isn't it annoying when you're taking a picture, but the background detracts from the actual substance of the image? I'd say it is. I need to know how much I should crop so that I get rid of this problem! But - as usual - I am quite lazy, so I need someone to do this for me...

Task & Rules

Given a binary matrix representing the image, output the dimensions (width and height) of the smallest sub-matrix that contains all the \$1\$s in the original matrix. A sub-matrix is a block of adjacent entries from the original matrix. Equivalently, it is a new matrix formed by overlapping a subset of adjacent rows and a subset of adjacent columns of the original.

  • It is allowed to take the width and the height of the matrix as input as well.
  • You can take input and provide output through any standard method, while taking note that these loopholes are forbidden by default. This is , so try to complete the task in the least bytes you can manage in your language of choice.

Example

$$\left[\begin{matrix} \color{red}0&\color{red}0&\color{red}0&\color{red}0&\color{red}0&\color{red}0\\ \color{red}0&\color{blue}1&\color{blue}0&\color{blue}1&\color{blue}0&\color{blue}0\\ \color{red}0&\color{blue}1&\color{blue}1&\color{blue}0&\color{blue}1&\color{blue}1\\ \color{red}0&\color{blue}0&\color{blue}1&\color{blue}0&\color{blue}1&\color{blue}0\\ \color{red}0&\color{red}0&\color{red}0&\color{red}0&\color{red}0&\color{red}0\end{matrix}\right] \longrightarrow \left[\begin{matrix}1&0&1&0&0\\1&1&0&1&1\\0&1&0&1&0\end{matrix}\right]\longrightarrow(5,3)$$

Test cases

Input | Output

[[0,1,0,0,0,1,0]]
--> (5,1) or (1,5)

[[0,0,0,0,0],[0,1,0,1,0],[0,0,1,0,0]]
--> (3,2) or (2,3)

[[1,1,1,1],[0,0,0,0],[0,0,0,0],[1,0,0,0]]
--> (4,4)

[[0,0,0,0,0,0],[0,1,0,1,0,1],[0,0,0,0,0,0]]
--> (5,1) or (1,5)

[[0,0,0,0,0],[0,1,0,1,0],[0,0,1,0,0],[0,1,0,1,0],[0,0,0,0,0]]
--> (3,3)

[[0,0,0,0,0,0],[0,1,0,1,0,0],[0,1,1,0,1,1],[0,0,1,0,1,0],[0,0,0,0,0,0]]
--> (5,3) or (3,5)
Mr. Xcoder
  • 42.5k
  • 9
  • 81
  • 214