View Code of Problem 17

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int n = scanner.nextInt();
            int m = scanner.nextInt();
            int[][] l = new int[n][m];
            int max = 0;
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    l[i][j] = scanner.nextInt();
                }
            }
            for(int i=0;i<n;i++){
                for(int j=0;j<m;j++){
                    Queue<int[]> queue=new LinkedList<>();
                    queue.add(new int[]{i,j});
                    int t=dis(l,queue);
                    if(max<t){
                        max=t;
                    }
                }
            }
            System.out.println(max);
        }
    }

    public static int dis(int[][] l,Queue<int[]> queue){
        int[][] d = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        int ans = 0;

        while (!queue.isEmpty()) {
            int dis = Integer.MAX_VALUE;
            int[] ints = queue.remove();
            int rr = 0;
            int cc = 0;
            for (int k = 0; k < 4; k++) {
                int i = ints[0] + d[k][0];
                int j = ints[1] + d[k][1];
                if (i >= 0 && j >= 0 && i < l.length && j < l[0].length && l[i][j] > l[ints[0]][ints[1]]) {
                    if (dis > l[i][j] - l[ints[0]][ints[1]]) {
                        dis = l[i][j] - l[ints[0]][ints[1]];
                        rr = i;
                        cc = j;
                    }
                }
            }
            if(dis!=Integer.MAX_VALUE){
                queue.add(new int[]{rr,cc});
                ans++;
            }

        }
        return ans;
    }
}

Double click to view unformatted code.


Back to problem 17