In a game with a 2D grid map I'm facing the following situation:
I need to find the largest bounding square that surrounds the player position (the red dot). Or at least a bounding square of maximum size, as there could be more. Note: square, not rectangle.
In this case, it's fairly easy to see the largest square is 8x8:
If I add an obstacle in the map, the largest possibility is now 5x5:
I am looking for a fast and efficient way of finding the (or a) maximum square that contains the player position.
What I'm currently doing is kind of brute force:
- A 1x1 square is always possible (the player position itself).
- Then I try all possible 2*2 squares containing the player, that's 4 possible different squares, and for each I do a 2*2 loop, checking if all grid cells are clear (not walls or obstacles).
- If a 2*2 square is possible, then I try all possible 3*3 squares surrounding the player (that's 9 different squares) and for each I do a 3*3 loop, to check if there's no collission.
- Et cetera, until for size N*N no square is possible.
It works, it's very straightforward, but it feels very inefficient. Obviously I'm doing a lot of redundant checks here, and I'm wondering if there is a smarter / faster way to do this. Does anyone know of an algorithm to do this efficiently?
(edit) Important addition: besides the player moving around, obstacles or walls are dynamically added or moved, so caching or precalc optimizations are somewhat hard to implement here.