Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

How can you tell if the target is reachable other than finding a path?


You preprocess the grid into connected components, marking every grid cell with the CC it is in. Then before pathfinding check that the start and end are in the same component. This is an O(1) check, albeit with a potential of O(n log n) space required for storing the array of CC lookups.


Whoops, make that an O(log n) check, technically speaking, as the index of which CC a cell belongs to may take O(log n) space worst-case.

Though you can treat it as effectively O(1) time and O(n) space.


Check if either the source or destination are completely enclosed.


Until the algorithm runs out of nodes to explore it can't know that the destination is unreachable. Checking if a node is enclosed is determining if its graph is disjoint from the graph that the other node is on. The only way to prove the graphs are disjoint is to explore every node in the graph.


In this case it's enough to set the algorithm to "bi-directional". If one side is enclosed it will stop. This only breaks if both disjoint parts are infinite (for example, an infinite wall between start and end.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: