Swim in Rising Water



Another way to solve this problem (more efficiently) is to use Disjoint Set data structure (like in Kruskal's algorithm for finding minimum spanning tree). This way you can reduce time complexity down to O(N^2). We go from 0 to N^2 and choose a Point on the grid with that value. Then we merge it with all its neighbours whose value is less than this Point's value.