LeetCode 1631. 最小体力消耗路径

java两种方法击败50% -> 100%!

并查集

将所有边从小到大排序,每次拿一条边连接两点,然后判断一下 ( 0 , 0 ) (0, 0) (0,0) ( m − 1 , n − 1 ) (m - 1, n - 1) (m1,n1)是否联通,若联通这次加入的边就是最小体力消耗。

class Solution {
     
    int[] p;
    int[][] edges;
    int m, n, N, len;
    int find(int u){
     
        if(p[u] != u) p[u] = find(p[u]);
        return p[u];
    }
    public int minimumEffortPath(int[][] heights) {
     
        int m = heights.length, n = heights[0].length;
        N = m * n;
        p = new int[N];
        for(int i = 0; i < N; i++) p[i] = i;
        len = 2 * N - (m + n);
        edges = new int[len][3];
        int k = 0;
        for(int i = 0; i < m; i++){
     
            for(int j = 0; j < n; j++){
     
                if(i > 0){
     
                    edges[k][0] = (i - 1) * n + j;
                    edges[k][1] = i * n + j;
                    edges[k++][2] = Math.abs(heights[i][j] - heights[i - 1][j]);
                }
                if(j > 0){
     
                    edges[k][0] = i * n + j - 1;
                    edges[k][1] = i * n + j;
                    edges[k++][2] = Math.abs(heights[i][j] - heights[i][j - 1]);
                }
            }
        }
        Arrays.sort(edges, (x, y) -> x[2] - y[2]);
        for(int i = 0; i < len; i++){
     
            int rootA = find(edges[i][0]), rootB = find(edges[i][1]);
            if(rootA != rootB){
     
                p[rootA] = rootB;
            }
            if(find(0) == find(N - 1)) return edges[i][2];
        }
        return 0;
    }
}

image.png

二分法

非常秀的方法,写了一个深搜版本的,高度值从 1 − 1 0 6 1 - 10^6 1106,体力消耗也是在这个范围内,每次取中间值判断一下不超过这个体力消耗能不能从左上到右下,如果能,就缩小体力,如果不能就增大体力,直到找到一个最小值。

class Solution {
     
    int m, n;
    int[][] heights;
    int[] dx = {
     0, 1, 0, -1}, dy = {
     1, 0, -1, 0};
    boolean[][] visit;
    boolean dfs(int x, int y, int len){
     
        visit[x][y] = true;
        if(x == m - 1 && y == n - 1) return true;
        int flag = 0;
        for(int i = 0; i < 4; i++){
     
            int xx = x + dx[i], yy = y + dy[i];
            if(xx >= 0 && xx < m && yy >= 0 && yy < n && !visit[xx][yy] && Math.abs(heights[xx][yy] - heights[x][y]) <= len && dfs(xx, yy, len))
                return true;
            else flag++;
        }
        if(flag == 4) return false;
        else return true;
    }
    public int minimumEffortPath(int[][] heights) {
     
        m = heights.length; n = heights[0].length;
        this.heights = heights;
        visit = new boolean[m][n];
        int l = 0, r = 1000010;
        while(l < r){
     
            int mid = l + r >> 1;
            for(boolean[] v : visit) Arrays.fill(v, false);
            if(dfs(0, 0, mid)) r = mid;
            else l = mid + 1;
        }
        return l;
    }
}

LeetCode 1631. 最小体力消耗路径_第1张图片

我的博客:https://me.csdn.net/qq_20067165?ref=miniprofile

你可能感兴趣的:(dfs,java,leetcode)