I think of the matrix as getting more and more flooded each day, so instead of checking every day naively, I binary-search on the answer. For any given day d, I temporarily mark the first d cells in cells as water, then I check whether there is still a path of land from the top row to the bottom using BFS (or DFS). I start the search from every land cell in the top row and try to walk only through land. If I can still reach the bottom, then crossing is possible on day d, so I try a later day; if not, I try an earlier day. This way, I efficiently narrow down to the last day when crossing is still possible.
from collections import deque
