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 min = Integer.MAX_VALUE;
            int r = 0;
            int c = 0;
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    l[i][j] = scanner.nextInt();
                    if (min > l[i][j]) {
                        min = l[i][j];
                        r = i;
                        c = j;
                    }
                }
            }
            int[][] d = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
            Queue<int[]> queue = new LinkedList<>();
            queue.add(new int[]{r, c});
            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++;
                }

            }
            System.out.println(ans);
        }
    }
}

Double click to view unformatted code.


Back to problem 17