I am building a maze solver and recently I wanted to be able to draw over the grid without having to manually build mazes using arrays. Anyway, I sat down and thought "there has to be a more efficient way to figure out which cell the mouse has collided with on click event, instead of having to iterate over the whole grid which at worst case scenario costs O(n^2)
."
After some thinking I came up with the following solution.
I knew that the size of each grid was constant (in my case 16x16
) and I knew the position of the mouse. So I decided to divide mouse position by tileSize
and then round it down.
My question is if this is a better solution than iterating over the whole grid, cell by cell. I haven't seen anyone do it this way so I am wondering if there's some edge case that I haven't thought of which might not work with this solution.