Advertisement
vladimirVenkov

GreedyDwarfEditorial

Jun 21st, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Main {
  4.     public static void main(String[] args) {
  5.         Scanner in = new Scanner(System.in);
  6.  
  7.         int rows = in.nextInt();
  8.         int cols = in.nextInt();
  9.  
  10.         int startRow = 0;
  11.         int startCol = 0;
  12.  
  13.         int[][] matrix = new int[rows][cols];
  14.  
  15.         for (int r = 0; r < rows; r++) {
  16.             for (int c = 0; c < cols; c++) {
  17.                 matrix[r][c] = in.nextInt();
  18.                 if (matrix[r][c] == 0) {
  19.                     startRow = r;
  20.                     startCol = c;
  21.                 }
  22.             }
  23.         }
  24.  
  25.         int coins = 0;
  26.         int row = startRow;
  27.         int col = startCol;
  28.  
  29.         int[] dRows = {0, 0, -1, +1};
  30.         int[] dCols = {-1, +1, 0, 0};
  31.  
  32.  
  33.         while (true) {
  34.             int tempMax = 0;
  35.             int maxNextRow = row;
  36.             int maxNextCol = col;
  37.  
  38.             for (int direction = 0; direction < dRows.length; direction++) {
  39.                 int nextRow = row + dRows[direction];
  40.                 int nextCol = col + dCols[direction];
  41.  
  42.                 if (!inRange(nextRow, rows) || !inRange(nextCol, cols)) {
  43.                     continue;
  44.                 }
  45.  
  46.                 if (tempMax < matrix[nextRow][nextCol]) {
  47.                     tempMax = matrix[nextRow][nextCol];
  48.                     maxNextRow = nextRow;
  49.                     maxNextCol = nextCol;
  50.                 }
  51.             }
  52.  
  53.             if (tempMax == 0) {
  54.                 break;
  55.             }
  56.  
  57.             row = maxNextRow;
  58.             col = maxNextCol;
  59.             matrix[row][col]--;
  60.             coins++;
  61.         }
  62.  
  63.         System.out.println(coins);
  64.     }
  65.  
  66.     static boolean inRange(int value, int max) {
  67.         return 0 <= value && value < max;
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement