java - Greedy Recursive Search -
my professor gave assignment need search around given point in grid other spots makes group (in example need find number of spots in "l" shape within problem).
so grid 10x10, , professor has given spot start with. professor gave idea check neighboring spots, , add set, if spot newly found (which in set) recursively call method.
private spot findspots(set<spot> spots, set<spot> activespots, spot initial) { spot newspot = null; set<spot> activeset = new hashset<spot>(); checkaround(activeset, new spot(initial.i - 1, initial.j)); checkaround(activeset, new spot(initial.i + 1, initial.j)); checkaround(activeset, new spot(initial.i, initial.j - 1)); checkaround(activeset, new spot(initial.i, initial.j + 1)); (spot spot : activeset) { newspot = findspots(spots, activespots, spot); if (grid[newspot.i][newspot.j] == true) spots.add(newspot); } return newspot; } private boolean checkaround(set<spot> spots, spot spot) { if (!spots.contains(spot)) { spots.add(spot); return true; } return false; }
i know need boundary condition (or else stackoverflow exceptions), need in logic.
i know need boundary condition [...]
you said yourself. 1 key word boundary. need check if spot legal in grid, , stop exploring if not.
another stop condition if spot visited.
if implement these 2 stop conditions, , if perform these checks before making further recursive calls, find solution without overflowing stack.
something this:
private int countspots(set<spot> visited, spot spot) { if (!isvalid(spot) || visited.contains(spot)) { return 0; } visited.add(spot); int count = 1; count += countspots(visited, new spot(spot.x - 1, spot.y)); count += countspots(visited, new spot(spot.x + 1, spot.y)); count += countspots(visited, new spot(spot.x, spot.y + 1)); count += countspots(visited, new spot(spot.x, spot.y - 1)); return count; }
btw algorithm you're using variant of flood fill, see more info , tips , hints in wikipedia page.
Comments
Post a Comment