First terminology: Network / network runs horizontally "x" from left to right 1..N and vertically, similar to "y" from top to bottom. The found squares have vertices (angles), which we will designate clockwise 1..4. The first such angle that we will call TopLeft is the one with the lowest vertical value (y); if there are two (non-rotating quadrangle), this is the one that has the lower horizontal (x) value.
Algorithm: scan all the points and try to build a quandrangle with the given point in the form of vertex # 1, i.e. TopLeft. This results in the following pseudo-code:
// for each TopLeft candidate... for x1 = 1 to N-1 // TopLeft can never have x=N for y1 = 1 to N-1 // TopLeft van never have y=N // scan vertex #2 candidates... for x2 = x1+1 to N // #2 is always strictly to the right of #1 for y2 = y1 to N // #2 is never above #1 // resulting #3 coordinates x3 = x2 - (y2 - y1) if x3 < 1 then exit 'for y2' // all next y2 will also yield x3<1 y3 = y2 + (x2 - x1) if y3 > N then exit 'for y2' // all next y2 will also yield y3>N // resulting #4 x4 = x1 - (y2 - y1) if x4 < 1 then exit 'for y2' // all next y2 will also yield x4<1 y4 = y1 + (x2 - x1) if y4 > N then exit 'for x2' // all next x2 will also yield y4>N // colors ok? if grid(x1,y1)==grid(x2,y2) && grid(x1,y1)==grid(x3,y3) && grid(x1,y1)==grid(x4,y4) then // FOUND! count+=1 endif next y2 next x2 next y1 next x1
source share