Java: Contiguous region in a multi-dimensional array, used to implement a Latin Square

944 views Asked by At

I am writing a program that reads in a potential Latin Square and tells whether or not it is a valid latin square or not. Now I am trying tell if the region selected is a contiguous one or not.

The potential Latin Square and the location of the region are read in at the same time. The region [0,1][0,2][1,1][1,2] would be a valid region because it is contiguous; [0,0][0,2][1,1][1,2] would not be contiguous or valid because [0,0] can't be reached. How would I tell if they are contiguous?

2

There are 2 answers

0
Don Roby On

A reasonable approach to this problem is a flood fill algorithm.

Basically, start from any point in your region, and build a set of locations in your region that are connected to the starting point by marking all its neighbors in the region and then marking all of their neighbors in the region that aren't already marked. When there's nothing new to mark, you've located the maximal contiguous region containing your starting point. If it's not the whole region, the region is not contiguous.

0
mcdowella On

Your question suggests at least two easy checks, for different things. If you just want to check that every point is reachable from every other point, you can treat the points as nodes in a network, where [x,y] is linked to [x - 1, y], [x + 1, y], [x, y - 1], and [x, y + 1]. You can find all nodes reachable from a given starting node using depth first search. Do such a search from an arbitrary starting node. If you visit all the nodes, then the region selected is contiguous. I guess this is just flood fill coming from a different background.

For a latin square, is any contiguous region OK, or do you need an axis-aligned rectangle? For instance, if your contiguous region has just three points, is that OK? If you want to check for an axis-aligned rectangle, work out the maximum and minimum value of x and y in the set, and then check that you have every combination [a, b], where Xmin <= a <= Xmax and Ymin <= b <= Ymax.