larscheng / algo

0 stars 0 forks source link

【Day 42 】2023-12-27 - 778. 水位上升的泳池中游泳 #42

Open larscheng opened 7 months ago

larscheng commented 7 months ago

https://leetcode-cn.com/problems/swim-in-rising-water

larscheng commented 7 months ago

思路

二分查找+深度优先遍历

在方格数值区间[0,N*N-1]中找一个数作为等待时间,使其满足:存在从左上角到右下角的路径,且该数要最小

代码

public class Solution {

    private int N;

    public  int[][] DIRECTIONS = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    public int swimInWater(int[][] grid) {
        this.N = grid.length;
        int left = 0;
        int right = N * N - 1;
        while (left < right) {
            int mid = (left + right) / 2;
            boolean[][] visited = new boolean[N][N];
            if (grid[0][0] <= mid && dfs(grid, 0, 0, visited, mid)) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }

    private boolean dfs(int[][] grid, int x, int y, boolean[][] visited, int threshold) {
        visited[x][y] = true;
        for (int[] direction : DIRECTIONS) {
            int newX = x + direction[0];
            int newY = y + direction[1];
            if (inArea(newX, newY) && !visited[newX][newY] && grid[newX][newY] <= threshold) {
                if (newX == N - 1 && newY == N - 1) {
                    return true;
                }

                if (dfs(grid, newX, newY, visited, threshold)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean inArea(int x, int y) {
        return x >= 0 && x < N && y >= 0 && y < N;
    }
}

复杂度