Optimized LeetCode 1970 Solution with Incremental BFS

Recently solved "LeetCode 1970 – Last Day Where You Can Still Cross" and learned an interesting optimization. My first approach used DFS + binary search, which worked but wasn’t very efficient. Instead, I tried a reverse incremental BFS: - Start with all cells flooded - Unflood cells one by one in reverse order - Incrementally propagate reachability from the top row Each cell is processed at most once, giving amortized O(R×C) runtime — similar to Union-Find, but using BFS. Even if you’re not familiar with DSU, this method is intuitive: just track which cells are reachable from the top as you unflood the grid. While most online solutions use Union-Find or binary search + BFS/DFS, this incremental BFS approach is less commonly discussed and performs extremely well (~8× faster than DFS + binary search in Python). Sharing the solution here: 🔗 [https://lnkd.in/gVkzaSgj] #algorithms #problemSolving #softwareengineering

Guys, FYI: I attempted the same question using DSU as well, and the shocking thing is, this solution took less run time as compared to DSU 😎

To view or add a comment, sign in

Explore content categories