Replaced recursive BFS by much faster BFS algorithm