Problem 45431. Pitting corrosion on a metal plate: Count the number of pits
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(R1R2),abs(C1C2)) <= 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.
Solution Stats
Problem Comments

1 Comment
Why is rand out on these ? :)
Solution Comments
Show commentsProblem Recent Solvers22
Suggested Problems

Project Euler: Problem 6, Natural numbers, squares and sums.
2070 Solvers

Create a vector whose elements depend on the previous element
635 Solvers

144 Solvers

115 Solvers

Matrix of Multiplication Facts
106 Solvers
More from this Author19
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!