GridChecker free response answer

The GridChecker problem from the 2010 AP Computer Science Exam is typical of free response problems that test GridWorld: The AP Computer Science Case Study. The problem requires you to run multiple methods of the Grid interface with correct implicit and explicit parameters and to handle the return types.

Review the GridChecker free response problem with AP CS Tutor Brandon Horn.

GridChecker Part (a): actorWithMostNeighbors

public Actor actorWithMostNeighbors()
    List<Location> occupiedLocations = gr.getOccupiedLocations();

    if(occupiedLocations.size() == 0)
      return null;

    Location locWithMostNeighbors = occupiedLocations.get(0);
    for(Location loc : occupiedLocations)
      if(gr.getOccupiedAdjacentLocations(loc).size() > gr.getOccupiedAdjacentLocations(locWithMostNeighbors).size())
        locWithMostNeighbors = loc;

    return gr.get(locWithMostNeighbors);

GridChecker Part (b): getOccupiedWithinTwo

public List<Location> getOccupiedWithinTwo(Location loc)
  List<Location> occupiedWithinTwo = new ArrayList<Location>();

  for (int row = loc.getRow() - 2; row <= loc.getRow() + 2; row++)
   for (int col = loc.getCol() - 2; col <= loc.getCol() + 2; col++)
    Location locToCheck = new Location(row, col);

    if (gr.isValid(locToCheck) && gr.get(locToCheck) != null)


  return occupiedWithinTwo;

Get AP CS Help

2010 AP CS Exam Free Response Solutions

Recommended Practice Problems