Welcome to Subscribe On Youtube

1970. Last Day Where You Can Still Cross

Description

There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively.

Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered with water (i.e., changed to 1).

You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down).

Return the last day where it is possible to walk from the top to the bottom by only walking on land cells.

 

Example 1:

Input: row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]]
Output: 2
Explanation: The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.

Example 2:

Input: row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]]
Output: 1
Explanation: The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 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
Explanation: The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.

 

Constraints:

  • 2 <= row, col <= 2 * 104
  • 4 <= row * col <= 2 * 104
  • cells.length == row * col
  • 1 <= ri <= row
  • 1 <= ci <= col
  • All the values of cells are unique.

Solutions

  • class Solution {
        private int[] p;
        private int row;
        private int col;
        private boolean[][] grid;
        private int[][] dirs = new int[][] { {0, -1}, {0, 1}, {1, 0}, {-1, 0} };
    
        public int latestDayToCross(int row, int col, int[][] cells) {
            int n = row * col;
            this.row = row;
            this.col = col;
            p = new int[n + 2];
            for (int i = 0; i < p.length; ++i) {
                p[i] = i;
            }
            grid = new boolean[row][col];
            int top = n, bottom = n + 1;
            for (int k = cells.length - 1; k >= 0; --k) {
                int i = cells[k][0] - 1, j = cells[k][1] - 1;
                grid[i][j] = true;
                for (int[] e : dirs) {
                    if (check(i + e[0], j + e[1])) {
                        p[find(i * col + j)] = find((i + e[0]) * col + j + e[1]);
                    }
                }
                if (i == 0) {
                    p[find(i * col + j)] = find(top);
                }
                if (i == row - 1) {
                    p[find(i * col + j)] = find(bottom);
                }
                if (find(top) == find(bottom)) {
                    return k;
                }
            }
            return 0;
        }
    
        private int find(int x) {
            if (p[x] != x) {
                p[x] = find(p[x]);
            }
            return p[x];
        }
    
        private boolean check(int i, int j) {
            return i >= 0 && i < row && j >= 0 && j < col && grid[i][j];
        }
    }
    
  • class Solution {
    public:
        vector<int> p;
        int dirs[4][2] = { {0, -1}, {0, 1}, {1, 0}, {-1, 0} };
        int row, col;
    
        int latestDayToCross(int row, int col, vector<vector<int>>& cells) {
            int n = row * col;
            this->row = row;
            this->col = col;
            p.resize(n + 2);
            for (int i = 0; i < p.size(); ++i) p[i] = i;
            vector<vector<bool>> grid(row, vector<bool>(col, false));
            int top = n, bottom = n + 1;
            for (int k = cells.size() - 1; k >= 0; --k) {
                int i = cells[k][0] - 1, j = cells[k][1] - 1;
                grid[i][j] = true;
                for (auto e : dirs) {
                    if (check(i + e[0], j + e[1], grid)) {
                        p[find(i * col + j)] = find((i + e[0]) * col + j + e[1]);
                    }
                }
                if (i == 0) p[find(i * col + j)] = find(top);
                if (i == row - 1) p[find(i * col + j)] = find(bottom);
                if (find(top) == find(bottom)) return k;
            }
            return 0;
        }
    
        bool check(int i, int j, vector<vector<bool>>& grid) {
            return i >= 0 && i < row && j >= 0 && j < col && grid[i][j];
        }
    
        int find(int x) {
            if (p[x] != x) p[x] = find(p[x]);
            return p[x];
        }
    };
    
  • class Solution:
        def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:
            n = row * col
            p = list(range(n + 2))
            grid = [[False] * col for _ in range(row)]
            top, bottom = n, n + 1
    
            def find(x):
                if p[x] != x:
                    p[x] = find(p[x])
                return p[x]
    
            def check(i, j):
                return 0 <= i < row and 0 <= j < col and grid[i][j]
    
            for k in range(len(cells) - 1, -1, -1):
                i, j = cells[k][0] - 1, cells[k][1] - 1
                grid[i][j] = True
                for x, y in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
                    if check(i + x, j + y):
                        p[find(i * col + j)] = find((i + x) * col + j + y)
                if i == 0:
                    p[find(i * col + j)] = find(top)
                if i == row - 1:
                    p[find(i * col + j)] = find(bottom)
                if find(top) == find(bottom):
                    return k
            return 0
    
    
  • var p []int
    
    func latestDayToCross(row int, col int, cells [][]int) int {
    	n := row * col
    	p = make([]int, n+2)
    	for i := 0; i < len(p); i++ {
    		p[i] = i
    	}
    	grid := make([][]bool, row)
    	for i := 0; i < row; i++ {
    		grid[i] = make([]bool, col)
    	}
    	top, bottom := n, n+1
    	dirs := [4][2]int{ {0, -1}, {0, 1}, {1, 0}, {-1, 0} }
    	for k := len(cells) - 1; k >= 0; k-- {
    		i, j := cells[k][0]-1, cells[k][1]-1
    		grid[i][j] = true
    		for _, e := range dirs {
    			if check(i+e[0], j+e[1], grid) {
    				p[find(i*col+j)] = find((i+e[0])*col + j + e[1])
    			}
    		}
    		if i == 0 {
    			p[find(i*col+j)] = find(top)
    		}
    		if i == row-1 {
    			p[find(i*col+j)] = find(bottom)
    		}
    		if find(top) == find(bottom) {
    			return k
    		}
    	}
    	return 0
    }
    
    func check(i, j int, grid [][]bool) bool {
    	return i >= 0 && i < len(grid) && j >= 0 && j < len(grid[0]) && grid[i][j]
    }
    
    func find(x int) int {
    	if p[x] != x {
    		p[x] = find(p[x])
    	}
    	return p[x]
    }
    
  • function latestDayToCross(row: number, col: number, cells: number[][]): number {
        let [l, r] = [1, cells.length];
        const check = (k: number): boolean => {
            const g: number[][] = Array.from({ length: row }, () => Array(col).fill(0));
            for (let i = 0; i < k; ++i) {
                const [x, y] = cells[i];
                g[x - 1][y - 1] = 1;
            }
            const q: number[][] = [];
            for (let j = 0; j < col; ++j) {
                if (g[0][j] === 0) {
                    q.push([0, j]);
                    g[0][j] = 1;
                }
            }
            const dirs: number[] = [-1, 0, 1, 0, -1];
            for (const [x, y] of q) {
                if (x === row - 1) {
                    return true;
                }
                for (let i = 0; i < 4; ++i) {
                    const nx = x + dirs[i];
                    const ny = y + dirs[i + 1];
                    if (nx >= 0 && nx < row && ny >= 0 && ny < col && g[nx][ny] === 0) {
                        q.push([nx, ny]);
                        g[nx][ny] = 1;
                    }
                }
            }
            return false;
        };
        while (l < r) {
            const mid = (l + r + 1) >> 1;
            if (check(mid)) {
                l = mid;
            } else {
                r = mid - 1;
            }
        }
        return l;
    }
    
    
  • use std::collections::VecDeque;
    
    impl Solution {
        pub fn latest_day_to_cross(row: i32, col: i32, cells: Vec<Vec<i32>>) -> i32 {
            let mut l: i32 = 1;
            let mut r: i32 = cells.len() as i32;
            let m = row as usize;
            let n = col as usize;
    
            let check = |k: i32, cells: &Vec<Vec<i32>>| -> bool {
                let mut g = vec![vec![0i32; n]; m];
                for i in 0..k as usize {
                    let x = (cells[i][0] - 1) as usize;
                    let y = (cells[i][1] - 1) as usize;
                    g[x][y] = 1;
                }
                let dirs = [-1, 0, 1, 0, -1];
                let mut q: VecDeque<(usize, usize)> = VecDeque::new();
                for j in 0..n {
                    if g[0][j] == 0 {
                        q.push_back((0, j));
                        g[0][j] = 1;
                    }
                }
                while let Some((x, y)) = q.pop_front() {
                    if x == m - 1 {
                        return true;
                    }
                    for i in 0..4 {
                        let nx = x as i32 + dirs[i];
                        let ny = y as i32 + dirs[i + 1];
                        if nx >= 0
                            && nx < m as i32
                            && ny >= 0
                            && ny < n as i32
                            && g[nx as usize][ny as usize] == 0
                        {
                            q.push_back((nx as usize, ny as usize));
                            g[nx as usize][ny as usize] = 1;
                        }
                    }
                }
                false
            };
    
            while l < r {
                let mid = (l + r + 1) >> 1;
                if check(mid, &cells) {
                    l = mid;
                } else {
                    r = mid - 1;
                }
            }
            l
        }
    }
    
    
  • class UnionFind {
        private final int[] p;
        private final int[] size;
    
        public UnionFind(int n) {
            p = new int[n];
            size = new int[n];
            for (int i = 0; i < n; ++i) {
                p[i] = i;
                size[i] = 1;
            }
        }
    
        public int find(int x) {
            if (p[x] != x) {
                p[x] = find(p[x]);
            }
            return p[x];
        }
    
        public boolean union(int a, int b) {
            int pa = find(a), pb = find(b);
            if (pa == pb) {
                return false;
            }
            if (size[pa] > size[pb]) {
                p[pb] = pa;
                size[pa] += size[pb];
            } else {
                p[pa] = pb;
                size[pb] += size[pa];
            }
            return true;
        }
    }
    
    class Solution {
        public int latestDayToCross(int row, int col, int[][] cells) {
            int mn = cells.length;
            UnionFind uf = new UnionFind(mn + 2);
            int s = mn, t = mn + 1;
            int[][] g = new int[row][col];
            for (var e : g) {
                Arrays.fill(e, 1);
            }
            final int[] dirs = {-1, 0, 1, 0, -1};
            for (int i = mn - 1;; --i) {
                int x = cells[i][0] - 1, y = cells[i][1] - 1;
                g[x][y] = 0;
                for (int j = 0; j < 4; ++j) {
                    int nx = x + dirs[j], ny = y + dirs[j + 1];
                    if (nx >= 0 && nx < row && ny >= 0 && ny < col && g[nx][ny] == 0) {
                        uf.union(x * col + y, nx * col + ny);
                    }
                }
                if (x == 0) {
                    uf.union(s, x * col + y);
                }
                if (x == row - 1) {
                    uf.union(t, x * col + y);
                }
                if (uf.find(s) == uf.find(t)) {
                    return i;
                }
            }
        }
    }
    
    
  • class UnionFind {
    public:
        UnionFind(int n) {
            p = vector<int>(n);
            size = vector<int>(n, 1);
            iota(p.begin(), p.end(), 0);
        }
    
        bool unite(int a, int b) {
            int pa = find(a), pb = find(b);
            if (pa == pb) {
                return false;
            }
            if (size[pa] > size[pb]) {
                p[pb] = pa;
                size[pa] += size[pb];
            } else {
                p[pa] = pb;
                size[pb] += size[pa];
            }
            return true;
        }
    
        int find(int x) {
            if (p[x] != x) {
                p[x] = find(p[x]);
            }
            return p[x];
        }
    
    private:
        vector<int> p, size;
    };
    
    class Solution {
    public:
        int latestDayToCross(int row, int col, vector<vector<int>>& cells) {
            int mn = cells.size();
            UnionFind uf(mn + 2);
            int s = mn, t = mn + 1;
            vector<vector<int>> g(row, vector<int>(col, 1));
            const int dirs[5] = {0, 1, 0, -1, 0};
            for (int i = mn - 1;; --i) {
                int x = cells[i][0] - 1, y = cells[i][1] - 1;
                g[x][y] = 0;
                for (int j = 0; j < 4; ++j) {
                    int nx = x + dirs[j], ny = y + dirs[j + 1];
                    if (nx >= 0 && nx < row && ny >= 0 && ny < col && g[nx][ny] == 0) {
                        uf.unite(x * col + y, nx * col + ny);
                    }
                }
                if (x == 0) {
                    uf.unite(s, x * col + y);
                }
                if (x == row - 1) {
                    uf.unite(t, x * col + y);
                }
                if (uf.find(s) == uf.find(t)) {
                    return i;
                }
            }
        }
    };
    
    
  • class UnionFind:
        def __init__(self, n):
            self.p = list(range(n))
            self.size = [1] * n
    
        def find(self, x):
            if self.p[x] != x:
                self.p[x] = self.find(self.p[x])
            return self.p[x]
    
        def union(self, a, b):
            pa, pb = self.find(a), self.find(b)
            if pa == pb:
                return False
            if self.size[pa] > self.size[pb]:
                self.p[pb] = pa
                self.size[pa] += self.size[pb]
            else:
                self.p[pa] = pb
                self.size[pb] += self.size[pa]
            return True
    
    
    class Solution:
        def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:
            mn = len(cells)
            uf = UnionFind(mn + 2)
            s, t = mn, mn + 1
            dirs = (-1, 0, 1, 0, -1)
            g = [[1] * col for _ in range(row)]
            for i in range(mn - 1, -1, -1):
                x, y = cells[i][0] - 1, cells[i][1] - 1
                g[x][y] = 0
                for a, b in pairwise(dirs):
                    nx, ny = x + a, y + b
                    if 0 <= nx < row and 0 <= ny < col and g[nx][ny] == 0:
                        uf.union(x * col + y, nx * col + ny)
                if x == 0:
                    uf.union(y, s)
                if x == row - 1:
                    uf.union(x * col + y, t)
                if uf.find(s) == uf.find(t):
                    return i
    
    
  • type unionFind struct {
    	p, size []int
    }
    
    func newUnionFind(n int) *unionFind {
    	p := make([]int, n)
    	size := make([]int, n)
    	for i := range p {
    		p[i] = i
    		size[i] = 1
    	}
    	return &unionFind{p, size}
    }
    
    func (uf *unionFind) find(x int) int {
    	if uf.p[x] != x {
    		uf.p[x] = uf.find(uf.p[x])
    	}
    	return uf.p[x]
    }
    
    func (uf *unionFind) union(a, b int) bool {
    	pa, pb := uf.find(a), uf.find(b)
    	if pa == pb {
    		return false
    	}
    	if uf.size[pa] > uf.size[pb] {
    		uf.p[pb] = pa
    		uf.size[pa] += uf.size[pb]
    	} else {
    		uf.p[pa] = pb
    		uf.size[pb] += uf.size[pa]
    	}
    	return true
    }
    
    func latestDayToCross(row int, col int, cells [][]int) int {
    	mn := len(cells)
    	uf := newUnionFind(mn + 2)
    	s, t := mn, mn+1
    	g := make([][]int, row)
    	for i := range g {
    		g[i] = make([]int, col)
    		for j := range g[i] {
    			g[i][j] = 1
    		}
    	}
    	dirs := [5]int{-1, 0, 1, 0, -1}
    	for i := mn - 1; ; i-- {
    		x, y := cells[i][0]-1, cells[i][1]-1
    		g[x][y] = 0
    		for j := 0; j < 4; j++ {
    			nx, ny := x+dirs[j], y+dirs[j+1]
    			if nx >= 0 && nx < row && ny >= 0 && ny < col && g[nx][ny] == 0 {
    				uf.union(x*col+y, nx*col+ny)
    			}
    		}
    		if x == 0 {
    			uf.union(s, x*col+y)
    		}
    		if x == row-1 {
    			uf.union(t, x*col+y)
    		}
    		if uf.find(s) == uf.find(t) {
    			return i
    		}
    	}
    }
    
    
  • class UnionFind {
        p: number[];
        size: number[];
        constructor(n: number) {
            this.p = Array(n)
                .fill(0)
                .map((_, i) => i);
            this.size = Array(n).fill(1);
        }
    
        find(x: number): number {
            if (this.p[x] !== x) {
                this.p[x] = this.find(this.p[x]);
            }
            return this.p[x];
        }
    
        union(a: number, b: number): boolean {
            const [pa, pb] = [this.find(a), this.find(b)];
            if (pa === pb) {
                return false;
            }
            if (this.size[pa] > this.size[pb]) {
                this.p[pb] = pa;
                this.size[pa] += this.size[pb];
            } else {
                this.p[pa] = pb;
                this.size[pb] += this.size[pa];
            }
            return true;
        }
    }
    
    function latestDayToCross(row: number, col: number, cells: number[][]): number {
        const mn = cells.length;
        const uf = new UnionFind(row * col + 2);
        const [s, t] = [mn, mn + 1];
        const g: number[][] = Array.from({ length: row }, () => Array(col).fill(1));
        const dirs: number[] = [-1, 0, 1, 0, -1];
        for (let i = mn - 1; ; --i) {
            const [x, y] = [cells[i][0] - 1, cells[i][1] - 1];
            g[x][y] = 0;
            for (let j = 0; j < 4; ++j) {
                const [nx, ny] = [x + dirs[j], y + dirs[j + 1]];
                if (nx >= 0 && nx < row && ny >= 0 && ny < col && g[nx][ny] === 0) {
                    uf.union(x * col + y, nx * col + ny);
                }
            }
            if (x === 0) {
                uf.union(s, y);
            }
            if (x === row - 1) {
                uf.union(t, x * col + y);
            }
            if (uf.find(s) === uf.find(t)) {
                return i;
            }
        }
    }
    
    
  • struct UnionFind {
        p: Vec<usize>,
        size: Vec<usize>,
    }
    
    impl UnionFind {
        fn new(n: usize) -> Self {
            let mut p = vec![0; n];
            let mut size = vec![1; n];
            for i in 0..n {
                p[i] = i;
            }
            Self { p, size }
        }
    
        fn find(&mut self, x: usize) -> usize {
            if self.p[x] != x {
                let px = self.p[x];
                self.p[x] = self.find(px);
            }
            self.p[x]
        }
    
        fn union(&mut self, a: usize, b: usize) -> bool {
            let pa = self.find(a);
            let pb = self.find(b);
            if pa == pb {
                return false;
            }
            if self.size[pa] > self.size[pb] {
                self.p[pb] = pa;
                self.size[pa] += self.size[pb];
            } else {
                self.p[pa] = pb;
                self.size[pb] += self.size[pa];
            }
            true
        }
    }
    
    impl Solution {
        pub fn latest_day_to_cross(row: i32, col: i32, cells: Vec<Vec<i32>>) -> i32 {
            let mn = cells.len();
            let mut uf = UnionFind::new(mn + 2);
            let s = mn;
            let t = mn + 1;
            let row = row as usize;
            let col = col as usize;
    
            let mut g = vec![vec![1i32; col]; row];
            let dirs = [-1, 0, 1, 0, -1];
    
            let mut i = mn as i32 - 1;
            loop {
                let x = (cells[i as usize][0] - 1) as usize;
                let y = (cells[i as usize][1] - 1) as usize;
                g[x][y] = 0;
    
                for j in 0..4 {
                    let nx = x as i32 + dirs[j];
                    let ny = y as i32 + dirs[j + 1];
                    if nx >= 0
                        && nx < row as i32
                        && ny >= 0
                        && ny < col as i32
                        && g[nx as usize][ny as usize] == 0
                    {
                        uf.union(x * col + y, nx as usize * col + ny as usize);
                    }
                }
    
                if x == 0 {
                    uf.union(s, x * col + y);
                }
                if x == row - 1 {
                    uf.union(t, x * col + y);
                }
                if uf.find(s) == uf.find(t) {
                    return i;
                }
                i -= 1;
            }
        }
    }
    
    

All Problems

All Solutions