The following is my wordsearch solving algorithm. I'd greatly appreciate tips on how to improve it (e.g. improve efficiency, better approach, etc.):
public boolean traverse(Grid grid) {
for (int r = 0; r < grid.getRows(); r++) {
for (int c = 0; c < grid.getCols(); c++) {
for (Direction direction : Direction.values()) {
currentPoint.y = r;
currentPoint.x = c;
this.direction = direction;
if (find(grid, currentPoint, 0)) {
for (Point point : consideredPoints) {
grid.markLetterAt(point);
}
return true;
}
}
}
}
return false;
}
Direction
is an enum with all the cardinal directions (N, NE, S, NW, etc...). It has a method (updatePoint()
) which changes a Point
to the direction (e.g. NE does point.y -= 1
, point.x += 1
)
Here is find
:
private boolean find(Grid grid, Point point, int count) {
if (!grid.isValidLetter(point)) { // Checks if the point is valid (e.g not < 0)
consideredPoints.clear();
return false;
}
if (grid.getLetterAt(point).equals(word.substring(count, count + 1))) {
consideredPoints.add(new Point(point));
if (count == word.length() - 1) {
return true;
}
direction.updatePoint(point);
return find(grid, point, count + 1);
}
consideredPoints.clear();
return false;
}