improved grid algorithm