KenDoBG

Untitled

Jan 9th, 2022
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.00 KB | None | 0 0
  1. import java.util.*;
  2. import java.util.stream.Collectors;
  3.  
  4. public class Climbing {
  5.     public static int[][] matrix;
  6.     public static int currentSum;
  7.     public static Map<Integer, List<Integer>> results = new TreeMap<>();
  8.  
  9.     public static List<Integer> currentPath = new ArrayList<>();
  10.  
  11.     public static void main(String[] args) {
  12.         Scanner scanner = new Scanner(System.in);
  13.  
  14.         int rows = Integer.parseInt(scanner.nextLine());
  15.         int cols = Integer.parseInt(scanner.nextLine());
  16.         matrix = createMatrix(rows, scanner);
  17.         findPath(matrix.length - 1, matrix[0].length - 1);
  18.  
  19.         printResult();
  20.     }
  21.  
  22.     private static void printResult() {
  23.         int max = results.keySet().stream().max(Integer::compare).get();
  24.         List<Integer> path = results.get(max);
  25.         String pathAsString = path.stream()
  26.                 .map(String::valueOf)
  27.                 .collect(Collectors.joining(" "));
  28.         System.out.println(max);
  29.         System.out.println(pathAsString);
  30.     }
  31.  
  32.     private static void findPath(int row, int col) {
  33.         if (!isInBounds(row, col)) {
  34.             return;
  35.         }
  36.  
  37.  
  38.         currentSum += matrix[row][col];
  39.         currentPath.add(matrix[row][col]);
  40.  
  41.         if (row == 0 && col == 0) {
  42.             results.putIfAbsent(currentSum, new ArrayList<>(currentPath));
  43.         }
  44.  
  45.         findPath(row - 1, col);
  46.         findPath(row, col - 1);
  47.  
  48.  
  49.         currentSum -= matrix[row][col];
  50.         currentPath.remove(currentPath.size() - 1);
  51.     }
  52.  
  53.     private static boolean isInBounds(int row, int col) {
  54.         return row >= 0 && col >=0;
  55.     }
  56.  
  57.  
  58.     private static int[][] createMatrix(int rows, Scanner scanner) {
  59.         int[][] matrix = new int[rows][];
  60.  
  61.         for (int i = 0; i < rows; i++) {
  62.             int[] arr = Arrays.stream(scanner.nextLine().split("\\s+"))
  63.                     .mapToInt(Integer::parseInt)
  64.                     .toArray();
  65.             matrix[i] = arr;
  66.         }
  67.         return matrix;
  68.     }
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment