You are given an N x M matrix of ones and zeros, which represents an image of a rectangular metal plate taken from the hull of a ship. Each element of the matrix denotes an area of the plate: The ones denote areas where the plate has corroded visibly, whereas zeros are areas where the metal is still in good condition. The corroded areas (the matrix elements with ones) can be found at multiple points on the metal plate.
A collection of corroded areas that are next to each other is called a pit. Pits can come at different sizes, depending on how much they grew over the years. Pitting corrosion is important to quantify because it gives an idea of the reliability of the ship structure.
For this problem, a pit is defined more clearly as follows: Two corroded areas at [row R1, column C1] and [row R2, column C2] belong to the same pit if and only if max(abs(R1-R2),abs(C1-C2)) <= 1. In other words, if two corroded areas are adjacent horizontally, vertically, or diagonally, then both are considered to belong to the same pit.
Write a function that accepts a matrix X denoting the image in question. Output the number of distinct separate pits found in this image. You are ensured that the size of the matrix is constrained at 1 <= N <= 20 and 1 <= M <= 20.
As an example, consider the following 10 x 10 image (left). The corroded areas that belong to the same pit are then labeled, showing that there are 5 distinct separate pits (right).
Sample test case: X = [0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 4 4 0 0 0 0 1 0 0 0 1 1 0 0 0 0 1 0 0 0 4 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 2 0 0 0 0 5 0 0 0 0 0 1 0 0 0 1 1 0 0 0 0 2 0 0 0 5 5 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 5 0 0 0 0 0 1 1 0 0 0 0]; 0 0 0 0 3 3 0 0 0 0 There are 5 pits in this image.
Why is rand out on these ? :)
Find all elements less than 0 or greater than 10 and replace them with NaN
15584 Solvers
156 Solvers
Back to basics 2 - Function Path
156 Solvers
middleAsColumn: Return all but first and last element as a column vector
393 Solvers
Return the first and last character of a string
2550 Solvers