Problem 673. Borderline Connectivity
Compute the connected components of pixel borders.
Suppose that h and v together describe a logical labeling of the borders between matrix elements, with h representing the horizontal borders, and v representing the vertical borders. If the original matrix is MxN, then h will be (M+1)xN and v will be Mx(N+1) with external borders included, or (M1)xN and Mx(N1) respectively if external borders are not included. Your solution should work with either sort of input.
It should return lh and lv, a labeling on h and v. These will be the same size as h and v, and zero wherever h and v are zero. Where h and v are nonzero, lh and lv will be an integer label indicating membership in some connected border component. Two border locations are in the same component if they are connected by sequentially adjacent border segments whose h and v values are all 1. Two border locations are adjacent if they meet at a corner. Thus, h(i,j) is adjacent to h(i,j1) and h(i,j+1), as well as v(i,j), v(i+1,j), v(i,j+1), and v(i+1,j+1) when external borders are included.
An example may make this clearer. Consider an original matrix of size 2x4, and the following border matrices:
h = [1 1 0 0; 0 0 1 0; 0 0 0 1]; v = [0 0 1 0 1; 1 0 0 1 1];
This corresponds to the following picture, where nonzero elements of h are shown as , elements of v are shown as , corners are shown as +, and the eight elements of the original matrix are indicated by their index:
+++ + + 1 35 7 + + ++ + 2 4 68 + + + ++
As can be seen in the diagram, there are two separate groups of edges. They will be labeled 1 and 2 in the final labeling.
(Originally I wanted to call this problem "Snakes on a Plane", but that name is already taken.)
Solution Stats
Solution Comments
Show commentsProblem Recent Solvers4
Suggested Problems

Find relatively common elements in matrix rows
2027 Solvers

Number of 1s in the Binary Representation of a Number
441 Solvers

Return elements unique to either input
759 Solvers

73 Solvers

When can one be the Life Member of the IEEE?
74 Solvers
More from this Author11
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!