In such a simple situation, you can perform the following three steps: find the centroid of your figure, sort the objects of interest based on the angle between the x axis and the line formed by the current point and the centroid, and go through the sorted points.
Given the situation, the x-coordinate of the center of gravity is the sum of the x-coordinates of each point of interest divided by the total number of objects of interest (respectively, for the y-coordinate of the centroid). To calculate angles, just use atan2, available in almost any language. Your interests are those that are represented as 1 or 5, otherwise it is not an angle (based on your input).
Do not be fooled that Hugh will solve your question, that is, he will not give the sorted coordinates that you are after. This is also an expensive method. In addition, given your matrix, you already have such ideal information that no other method will beat (the problem, of course, repeats such a good result as you presented), in those cases, Hugh may be useful).
My Ruby is pretty bad, so take the following code as a recommendation for your problem:
include Math data = ["0000000000000000", "0000053335000000", "0000030003000000", "0000030003000000", "0000020002000000", "0533210001233500", "0300000000000300", "0300000000000300", "0300000000000300", "0533210001233500", "0000020002000000", "0000030003000000", "0000030003000000", "0000053335000000", "0000000000000000", "0000000000000000"] corner_x = [] corner_y = [] data.each_with_index{|line, i| line.split(//).each_with_index{|col, j| if col == "1" || col == "5" # Cartesian coords. corner_x.push(j + 1) corner_y.push(data.length - i) end } } centroid_y = corner_y.reduce(:+)/corner_y.length.to_f centroid_x = corner_x.reduce(:+)/corner_x.length.to_f corner = [] corner_x.zip(corner_y).each{|c| dy = c[1] - centroid_y dx = c[0] - centroid_x theta = Math.atan2(dy, dx) corner.push([theta, c]) } corner.sort! corner.each_cons(2) {|c| puts "%s->%s" % [c[0][1].inspect, c[1][1].inspect] }
This leads to:
[2, 7]->[6, 7] [6, 7]->[6, 3] [6, 3]->[10, 3] [10, 3]->[10, 7] [10, 7]->[14, 7] [14, 7]->[14, 11] [14, 11]->[10, 11] [10, 11]->[10, 15] [10, 15]->[6, 15] [6, 15]->[6, 11] [6, 11]->[2, 11]
What are your vertices clockwise, starting from the bottom left side (in Cartesian coordinates, starting at (1, 1) in the left-most lower position).