Skip to content
JZLeetCode
Go back

LeetCode 1970 Last Day Where You Can Still Cross

Table of contents

Open Table of contents

Description

Question Links: LeetCode 1970

The matrix starts as land on day 0. Each day, the next coordinate in cells becomes water. Find the last day when a path still connects any land cell in the top row to any land cell in the bottom row. The path can move up, down, left, or right.

Example 1

Input: row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]]

Output: 2

Example 2

Input: row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]]

Output: 1

Example 3

Input: row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]]

Output: 3

Constraints:

Idea

Let N = row * col. One flood happens per day, so reachability is monotonic: once the top and bottom are disconnected, later days cannot restore a land path.

1. Binary Search + BFS

Precompute floodDay[r][c], the day that cell becomes water. For a candidate day d, the cell is land exactly when floodDay[r][c] > d. Start a BFS from every land cell in the top row and check whether it reaches the bottom row.

Binary search the day from 0 through N. Each reachability check visits at most N cells, so the time complexity is O(Nlog⁡N)O(N \log N) and the extra space is O(N)O(N).

2. Reverse Flooding + Union-Find

Start after all cells have flooded, then reopen them in reverse order. Each reopened cell is unioned with its open neighbors. Join every open top-row cell to a virtual TOP node and every open bottom-row cell to a virtual BOTTOM node.

TOP
 |
 A---B      active land cells join when adjacent
     |
 C---D
 |
BOTTOM

When reopening cells[i] first connects TOP and BOTTOM, the grid is back to the state after i flood days, so i is the answer. Each cell and each of its four neighbors is processed once; union-find makes the time O(Nα(N))O(N \alpha(N)), with O(N)O(N) extra space.

Java

package graph;

import java.util.ArrayDeque;
import java.util.Queue;

/**
 * LeetCode 1970: Last Day Where You Can Still Cross.
 *
 * <p>Cells are flooded in the given 1-based order. Return the last day on which a land path can
 * connect any cell in the top row to any cell in the bottom row.</p>
 */
public final class LastDayWhereYouCanStillCross {

    private LastDayWhereYouCanStillCross() {
    }

    /**
     * Binary search the last feasible day; BFS checks whether a land crossing remains.
     * Time: O(row * col * log(row * col)); space: O(row * col).
     */
    public static int latestDayToCrossBfs(int row, int col, int[][] cells) {
        int[][] floodDay = new int[row][col];
        for (int i = 0; i < cells.length; i++) {
            floodDay[cells[i][0] - 1][cells[i][1] - 1] = i + 1;
        }

        int low = 0;
        int high = cells.length;
        int latest = 0;
        while (low <= high) {
            int day = low + (high - low) / 2;
            if (canCross(day, row, col, floodDay)) {
                latest = day;
                low = day + 1;
            } else {
                high = day - 1;
            }
        }
        return latest;
    }

    private static boolean canCross(int day, int row, int col, int[][] floodDay) {
        boolean[][] visited = new boolean[row][col];
        Queue<Integer> queue = new ArrayDeque<>();
        for (int c = 0; c < col; c++) {
            if (floodDay[0][c] > day) {
                visited[0][c] = true;
                queue.offer(c);
            }
        }

        int[] rowStep = {-1, 1, 0, 0};
        int[] colStep = {0, 0, -1, 1};
        while (!queue.isEmpty()) {
            int cell = queue.remove();
            int r = cell / col;
            int c = cell % col;
            if (r == row - 1) {
                return true;
            }

            for (int direction = 0; direction < rowStep.length; direction++) {
                int nextRow = r + rowStep[direction];
                int nextCol = c + colStep[direction];
                if (nextRow < 0 || nextRow >= row || nextCol < 0 || nextCol >= col
                        || visited[nextRow][nextCol] || floodDay[nextRow][nextCol] <= day) {
                    continue;
                }
                visited[nextRow][nextCol] = true;
                queue.offer(nextRow * col + nextCol);
            }
        }
        return false;
    }

    /**
     * Reverse the flood order and join adjacent land cells with union-find.
     * Time: O(row * col * alpha(row * col)); space: O(row * col).
     */
    public static int latestDayToCrossUnionFind(int row, int col, int[][] cells) {
        int totalCells = row * col;
        int top = totalCells;
        int bottom = totalCells + 1;
        boolean[][] land = new boolean[row][col];
        DisjointSet sets = new DisjointSet(totalCells + 2);
        int[] rowStep = {-1, 1, 0, 0};
        int[] colStep = {0, 0, -1, 1};

        for (int i = cells.length - 1; i >= 0; i--) {
            int r = cells[i][0] - 1;
            int c = cells[i][1] - 1;
            land[r][c] = true;
            int cell = r * col + c;
            if (r == 0) {
                sets.union(cell, top);
            }
            if (r == row - 1) {
                sets.union(cell, bottom);
            }

            for (int direction = 0; direction < rowStep.length; direction++) {
                int nextRow = r + rowStep[direction];
                int nextCol = c + colStep[direction];
                if (nextRow >= 0 && nextRow < row && nextCol >= 0 && nextCol < col
                        && land[nextRow][nextCol]) {
                    sets.union(cell, nextRow * col + nextCol);
                }
            }

            if (sets.connected(top, bottom)) {
                // Reopening cells[i] restores the grid after day i (0-indexed).
                return i;
            }
        }
        return 0;
    }

    private static final class DisjointSet {
        private final int[] parent;
        private final int[] size;

        private DisjointSet(int count) {
            parent = new int[count];
            size = new int[count];
            for (int i = 0; i < count; i++) {
                parent[i] = i;
                size[i] = 1;
            }
        }

        private int find(int value) {
            if (parent[value] != value) {
                parent[value] = find(parent[value]);
            }
            return parent[value];
        }

        private void union(int first, int second) {
            int firstRoot = find(first);
            int secondRoot = find(second);
            if (firstRoot == secondRoot) {
                return;
            }
            if (size[firstRoot] < size[secondRoot]) {
                int swap = firstRoot;
                firstRoot = secondRoot;
                secondRoot = swap;
            }
            parent[secondRoot] = firstRoot;
            size[firstRoot] += size[secondRoot];
        }

        private boolean connected(int first, int second) {
            return find(first) == find(second);
        }
    }
}

Python

"""LeetCode 1970: Last Day Where You Can Still Cross."""

from collections import deque


class Solution:
    def latestDayToCrossBfs(self, row: int, col: int, cells: list[list[int]]) -> int:
        """Binary search the day and test reachability with BFS.

        Time: O(row * col * log(row * col)); space: O(row * col).
        """
        flood_day = [[0] * col for _ in range(row)]
        for day, (r, c) in enumerate(cells, start=1):
            flood_day[r - 1][c - 1] = day

        low, high = 0, len(cells)
        latest = 0
        while low <= high:
            day = (low + high) // 2
            if self._can_cross(day, row, col, flood_day):
                latest = day
                low = day + 1
            else:
                high = day - 1
        return latest

    @staticmethod
    def _can_cross(day: int, row: int, col: int, flood_day: list[list[int]]) -> bool:
        # Each cell is visited at most once, so this check is O(row * col) time and space.
        visited = [[False] * col for _ in range(row)]
        queue = deque()
        for c in range(col):
            if flood_day[0][c] > day:
                visited[0][c] = True
                queue.append((0, c))

        directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
        while queue:
            r, c = queue.popleft()
            if r == row - 1:
                return True
            for dr, dc in directions:  # Four neighbors per cell: O(1) work per visit.
                nr, nc = r + dr, c + dc
                if (
                    0 <= nr < row
                    and 0 <= nc < col
                    and not visited[nr][nc]
                    and flood_day[nr][nc] > day
                ):
                    visited[nr][nc] = True
                    queue.append((nr, nc))
        return False

    def latestDayToCrossUnionFind(self, row: int, col: int, cells: list[list[int]]) -> int:
        """Undo floods and join neighboring land with disjoint sets.

        Time: O(row * col * alpha(row * col)); space: O(row * col).
        """
        total = row * col
        top, bottom = total, total + 1
        parent = list(range(total + 2))
        size = [1] * (total + 2)
        land = [[False] * col for _ in range(row)]
        directions = ((1, 0), (-1, 0), (0, 1), (0, -1))

        for i in range(total - 1, -1, -1):
            r, c = cells[i][0] - 1, cells[i][1] - 1
            land[r][c] = True
            cell = r * col + c
            if r == 0:
                self._union(parent, size, cell, top)
            if r == row - 1:
                self._union(parent, size, cell, bottom)

            for dr, dc in directions:  # Four neighbors give O(1) unions per opened cell.
                nr, nc = r + dr, c + dc
                if 0 <= nr < row and 0 <= nc < col and land[nr][nc]:
                    self._union(parent, size, cell, nr * col + nc)

            if self._find(parent, top) == self._find(parent, bottom):
                # Reopening cells[i] restores the grid after i flood days.
                return i
        return 0

    @staticmethod
    def _find(parent: list[int], node: int) -> int:
        while parent[node] != node:
            parent[node] = parent[parent[node]]
            node = parent[node]
        return node

    @classmethod
    def _union(cls, parent: list[int], size: list[int], a: int, b: int) -> None:
        root_a, root_b = cls._find(parent, a), cls._find(parent, b)
        if root_a == root_b:
            return
        if size[root_a] < size[root_b]:
            root_a, root_b = root_b, root_a
        parent[root_b] = root_a
        size[root_a] += size[root_b]

C++

#ifndef LEETCODE_LASTDAYWHEREYOUCANSTILLCROSS_HPP
#define LEETCODE_LASTDAYWHEREYOUCANSTILLCROSS_HPP

#include <algorithm>
#include <numeric>
#include <queue>
#include <vector>

using namespace std;

class Solution1970 {
private:
    class UnionFind {
    private:
        vector<int> parent;
        vector<int> size;

    public:
        explicit UnionFind(int n) : parent(n), size(n, 1) {
            iota(parent.begin(), parent.end(), 0);
        }

        int find(int x) {
            if (parent[x] != x) {
                parent[x] = find(parent[x]);
            }
            return parent[x];
        }

        void unite(int a, int b) {
            int rootA = find(a);
            int rootB = find(b);
            if (rootA == rootB) {
                return;
            }

            if (size[rootA] < size[rootB]) {
                swap(rootA, rootB);
            }
            parent[rootB] = rootA;
            size[rootA] += size[rootB];
        }
    };

    static bool canCross(int row, int col, vector<vector<int>>& cells, int days) {
        vector<vector<bool>> water(row, vector<bool>(col, false));
        for (int i = 0; i < days; ++i) {
            water[cells[i][0] - 1][cells[i][1] - 1] = true;
        }

        vector<vector<bool>> visited(row, vector<bool>(col, false));
        queue<pair<int, int>> pending;
        for (int c = 0; c < col; ++c) {
            if (!water[0][c]) {
                pending.emplace(0, c);
                visited[0][c] = true;
            }
        }

        const int directions[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        while (!pending.empty()) {
            auto [r, c] = pending.front();
            pending.pop();
            if (r == row - 1) {
                return true;
            }

            for (const auto& direction : directions) {
                int nr = r + direction[0];
                int nc = c + direction[1];
                if (nr < 0 || nr >= row || nc < 0 || nc >= col ||
                    water[nr][nc] || visited[nr][nc]) {
                    continue;
                }
                visited[nr][nc] = true;
                pending.emplace(nr, nc);
            }
        }
        return false;
    }

public:
    // Binary search + BFS: O(R*C*log(R*C)) time and O(R*C) space.
    static int latestDayToCrossBfs(int row, int col, vector<vector<int>>& cells) {
        int low = 0;
        int high = static_cast<int>(cells.size());
        int latestDay = 0;

        while (low <= high) {
            int days = low + (high - low) / 2;
            if (canCross(row, col, cells, days)) {
                latestDay = days;
                low = days + 1;
            } else {
                high = days - 1;
            }
        }
        return latestDay;
    }

    // Reverse-time union-find: O(R*C*alpha(R*C)) time and O(R*C) space.
    static int latestDayToCrossUnionFind(int row, int col, vector<vector<int>>& cells) {
        int cellCount = row * col;
        int top = cellCount;
        int bottom = cellCount + 1;
        UnionFind components(cellCount + 2);
        vector<vector<bool>> land(row, vector<bool>(col, false));
        const int directions[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

        for (int day = static_cast<int>(cells.size()) - 1; day >= 0; --day) {
            int r = cells[day][0] - 1;
            int c = cells[day][1] - 1;
            land[r][c] = true;
            int current = r * col + c;

            if (r == 0) {
                components.unite(current, top);
            }
            if (r == row - 1) {
                components.unite(current, bottom);
            }

            for (const auto& direction : directions) {
                int nr = r + direction[0];
                int nc = c + direction[1];
                if (nr >= 0 && nr < row && nc >= 0 && nc < col && land[nr][nc]) {
                    components.unite(current, nr * col + nc);
                }
            }

            if (components.find(top) == components.find(bottom)) {
                // Reopening cells[day] restores the grid at the end of day `day`.
                return day;
            }
        }
        return 0;
    }
};

#endif // LEETCODE_LASTDAYWHEREYOUCANSTILLCROSS_HPP

Rust

use std::collections::VecDeque;

pub struct Solution;

impl Solution {
    /// Binary search the latest day and flood-fill to check reachability.
    /// Building the flood calendar and each BFS take O(row * col), and the
    /// binary search makes the total O(row * col * log(row * col)) time.
    /// The flood calendar, visited grid, and queue use O(row * col) space.
    pub fn latest_day_to_cross_bfs(row: i32, col: i32, cells: Vec<Vec<i32>>) -> i32 {
        if row <= 0 || col <= 0 || cells.is_empty() {
            return 0;
        }

        let rows = row as usize;
        let cols = col as usize;
        let mut flooded_on = vec![vec![0; cols]; rows];
        for (day, cell) in cells.iter().enumerate() {
            flooded_on[(cell[0] - 1) as usize][(cell[1] - 1) as usize] = (day + 1) as i32;
        }

        let mut low = 0;
        let mut high = cells.len() as i32;
        let mut latest = 0;
        while low <= high {
            let day = low + (high - low) / 2;
            if Self::can_cross(day, &flooded_on, rows, cols) {
                latest = day;
                low = day + 1;
            } else {
                high = day - 1;
            }
        }
        latest
    }

    /// Reverse the flooding order and join adjacent land cells as they open.
    /// Each cell is activated once and each of its four edges is processed
    /// once, for O(row * col * alpha(row * col)) time and O(row * col) space.
    pub fn latest_day_to_cross_union_find(row: i32, col: i32, cells: Vec<Vec<i32>>) -> i32 {
        if row <= 0 || col <= 0 || cells.is_empty() {
            return 0;
        }

        let rows = row as usize;
        let cols = col as usize;
        let cell_count = rows * cols;
        let top = cell_count;
        let bottom = cell_count + 1;
        let mut parent: Vec<usize> = (0..cell_count + 2).collect();
        let mut size = vec![1; cell_count + 2];
        let mut land = vec![false; cell_count];
        let directions = [(-1isize, 0isize), (1, 0), (0, -1), (0, 1)];

        for day_index in (0..cells.len()).rev() {
            let r = (cells[day_index][0] - 1) as usize;
            let c = (cells[day_index][1] - 1) as usize;
            let id = r * cols + c;
            land[id] = true;

            if r == 0 {
                Self::union(&mut parent, &mut size, id, top);
            }
            if r + 1 == rows {
                Self::union(&mut parent, &mut size, id, bottom);
            }

            for (dr, dc) in directions {
                let nr = r as isize + dr;
                let nc = c as isize + dc;
                if nr < 0 || nr >= rows as isize || nc < 0 || nc >= cols as isize {
                    continue;
                }
                let neighbor = nr as usize * cols + nc as usize;
                if land[neighbor] {
                    Self::union(&mut parent, &mut size, id, neighbor);
                }
            }

            if Self::find(&mut parent, top) == Self::find(&mut parent, bottom) {
                // Opening cells[day_index] restores the grid after day_index floods.
                return day_index as i32;
            }
        }
        0
    }

    fn can_cross(day: i32, flooded_on: &[Vec<i32>], rows: usize, cols: usize) -> bool {
        let mut visited = vec![vec![false; cols]; rows];
        let mut queue = VecDeque::new();
        for c in 0..cols {
            if flooded_on[0][c] > day {
                visited[0][c] = true;
                queue.push_back((0usize, c));
            }
        }

        let directions = [(-1isize, 0isize), (1, 0), (0, -1), (0, 1)];
        while let Some((r, c)) = queue.pop_front() {
            if r + 1 == rows {
                return true;
            }
            for (dr, dc) in directions {
                let nr = r as isize + dr;
                let nc = c as isize + dc;
                if nr < 0 || nr >= rows as isize || nc < 0 || nc >= cols as isize {
                    continue;
                }
                let (nr, nc) = (nr as usize, nc as usize);
                if !visited[nr][nc] && flooded_on[nr][nc] > day {
                    visited[nr][nc] = true;
                    queue.push_back((nr, nc));
                }
            }
        }
        false
    }

    fn find(parent: &mut [usize], x: usize) -> usize {
        if parent[x] != x {
            parent[x] = Self::find(parent, parent[x]);
        }
        parent[x]
    }

    fn union(parent: &mut [usize], size: &mut [usize], a: usize, b: usize) {
        let mut root_a = Self::find(parent, a);
        let mut root_b = Self::find(parent, b);
        if root_a == root_b {
            return;
        }
        if size[root_a] < size[root_b] {
            std::mem::swap(&mut root_a, &mut root_b);
        }
        parent[root_b] = root_a;
        size[root_a] += size[root_b];
    }
}
Share this post on:

Next Post
System Design - How Kubernetes StatefulSets Keep Pod Identity and Storage