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 (M-1)xN and Mx(N-1) 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,j-1) 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 3|5 7| + + +-+ + |2 4 6|8| + + + +-+
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.)
1506 Solvers
Project Euler: Problem 8, Find largest product in a large string of numbers
186 Solvers
17 Solvers
mathematics , probability problem
31 Solvers
Geometry: Find Circle given 3 Non-Colinear Points
41 Solvers
Tags