Fixed the issue with the space. I was adding new space for each BFS cycle, so no wonder it was behaving quadratically. Now, I use a temporary variable for the space in the loop and use the iteration with the largest space usage