another optimization to BFS