13
1
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.
- The input is guaranteed to contain at least one \$1\$.
- You can take input and provide output through any standard method, while taking note that these loopholes are forbidden by default. This is code-golf, 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)
1This feels very familiar; was it in the Sandbox for a while? – Shaggy – 2018-10-27T23:00:23.073
8This is indeed very close to the linked question but I think it can be considered a distant enough subset thereof because generating the matrix is not absolutely necessary for computing the actual width and height. For instance, one possible algorithm would be to count the minimal number of marginal zeros for each row and column and subtract those from the original dimensions. – Mr. Xcoder – 2018-10-28T10:08:48.680
related - Highlight the Bounding Box, Part I: Cartesian Grid – Jonathan Allan – 2018-10-28T13:57:44.820