Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.Arrays;
- import java.util.Locale;
- import java.util.Scanner;
- public class ScroogeMcDuck {
- public static void main(String[] args) throws IOException {
- Scanner input = new Scanner(System.in).useLocale(Locale.US);
- int[] coordinates = Arrays.stream(input.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
- int row = coordinates[0];
- int column = coordinates[1];
- int[][] field = new int[row][column];
- for (int i = 0; i < row; i++) {
- for (int j = 0; j < column; j++) {
- field[i][j] = input.nextInt();
- if (field[i][j] == 0) {
- coordinates[0] = i;
- coordinates[1] = j;
- }
- }
- }
- boolean exit = false;
- int sum = 0;
- while (!exit) {
- int x = coordinates[0];
- int y = coordinates[1];
- int left = 0;
- int right = 0;
- int up = 0;
- int down = 0;
- if (x - 1 >= 0) {
- up = field[x - 1][y];
- } else {
- up = -1;
- }
- if (x + 1 <=row-1) {
- down = field[x + 1][y];
- } else {
- down = -1;
- }
- if (y - 1 >= 0) {
- left = field[x][y-1];
- } else {
- left = -1;
- }
- if (y + 1 <= column-1) {
- right = field[x][y+1];
- } else {
- right = -1;
- }
- String bestMove = calculateMax(up, down, left, right);
- if (bestMove == "wrong") {
- int secondBest = calculateEqual(up, down, left, right);
- if (left == secondBest) {
- bestMove = "left";
- } else if (right == secondBest) {
- bestMove = "right";
- } else if (up == secondBest) {
- bestMove = "up";
- } else if (down == secondBest) {
- bestMove = "down";
- }
- }
- switch (bestMove) {
- case "up":
- x--;
- break;
- case "down":
- x++;
- break;
- case "left":
- y--;
- break;
- case "right":
- y++;
- break;
- }
- if (field[x][y] == 0) {
- exit = true;
- } else {
- coordinates[0] = x;
- coordinates[1] = y;
- field[x][y]--;
- sum++;
- }
- }
- System.out.println(sum);
- }
- public static String calculateMax(int a, int b, int c, int d) {
- if (a > b && a > c && a > d) {
- return "up";
- } else if (b > a && b > c && b > d) {
- return "down";
- } else if (c > b && c > a && c > d) {
- return "left";
- } else if (d > b && d > c && d > a) {
- return "right";
- } else {
- return "wrong";
- }
- }
- public static int calculateEqual(int a, int b, int c, int d) {
- if (a >= b && a >= c && a >= d) {
- return a;
- } else if (b >= a && b >= c && b >= d) {
- return b;
- } else if (c >= b && c >= a && c >= d) {
- return c;
- } else {
- return d;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement