leetcode778. 水位上升的泳池中游泳 两种方法

leetcode778. 水位上升的泳池中游泳

题目

leetcode778. 水位上升的泳池中游泳

解题的方法

dfs + 二分发

在这里二分的意思是在取值的范围类,进行二分的查找,看是否能够到达 右下角的元素。如果能够到达就ri(右边的边界) = mid缩小mid的值,如果不能够,就扩大mid的范围,就是le(左边的边界) = mid。当le == ri时 就是最小的值。

class Solution {
	class Road{
		int[][] board;
		int X_len, Y_len;
        int[] X = {1,-1,0,0};
		int[] Y = {0,0,-1,1};
		int res = 1000;
		public Road(int l1, int l2) {
			board = new int[l1][l2];
            board[0][0] = 1;
			X_len = l1;
			Y_len = l2;
		}
		public boolean dfs(int x, int y, int[][] grid, int mid) {
			int i = 0;
			int a,b;
			if(x == X_len - 1 && y == Y_len - 1) {
				return true;
			}
			for(i = 0; i < 4; i++){
				a = x + X[i];
				b = y + Y[i];
				if(a >= 0 && a < X_len && b < Y_len && b >= 0 && board[a][b] == 0 && grid[a][b] <= mid){
					board[a][b] = 1;
                    if(dfs(a, b, grid, mid)){
                        return true;
                    }
				}
			}
            return false;
		}
        public void clear(int l1, int l2){
            board = new int[l1][l2];
        }
	}
    public int swimInWater(int[][] grid) {
        int le = Math.max(grid[0][0],grid[grid.length - 1][grid[0].length - 1]), ri = 50 * 50 - 1;
        Road road = new Road(grid.length, grid[0].length);
        while(le < ri){
            int mid = (le + ri)>>1;
            //System.out.println("le = "+le+" mid = "+mid+" ri = "+ri);
            if(road.dfs(0, 0, grid, mid)) {
                ri = mid;
            }
            else{
                le = mid + 1;
            }
            road.clear(grid.length, grid[0].length);
        }
        return ri;
    }
}

地雷

原博客
最小的值(val)开始进行递增,如果值小于或等于val则把数组赋值为val,然后继续遍历下去就只要右下角的值等于val就说明这个值是最小适合的值(因为val是从最小的值进行递增的)

class Solution {
    int[] X = {0,0,-1,1};
    int[] Y = {1,-1,0,0};
    public void dfs(int m,int n, int m_len, int n_len, int val, int[][] grid){
        if(grid[m][n] >= val){
            return ;
        }
        grid[m][n] = val;
        for(int i = 0; i < 4; i++){
            int a = m + X[i];
            int b = n + Y[i];
            if(a >= 0 && a < m_len && b >= 0 && b < n_len){
                dfs(a,b,m_len,n_len,val, grid);
            }
        }
    }
    public int swimInWater(int[][] grid) {
        int i;
        int m_len = grid.length, n_len = grid[0].length;
        int val = Math.max(grid[0][0], grid[m_len - 1][n_len - 1]);
        while(true){
            dfs(0, 0, m_len, n_len, val + 1, grid);
            if(grid[m_len - 1][n_len - 1] == val + 1){
                return val;
            }
            val++;
        }
    }
}

你可能感兴趣的:(leetcode,算法,二分法,dfs)