Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.util.stream.Collectors;
- public class Climbing {
- public static int[][] matrix;
- public static int currentSum;
- public static Map<Integer, List<Integer>> results = new TreeMap<>();
- public static List<Integer> currentPath = new ArrayList<>();
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int rows = Integer.parseInt(scanner.nextLine());
- int cols = Integer.parseInt(scanner.nextLine());
- matrix = createMatrix(rows, scanner);
- findPath(matrix.length - 1, matrix[0].length - 1);
- printResult();
- }
- private static void printResult() {
- int max = results.keySet().stream().max(Integer::compare).get();
- List<Integer> path = results.get(max);
- String pathAsString = path.stream()
- .map(String::valueOf)
- .collect(Collectors.joining(" "));
- System.out.println(max);
- System.out.println(pathAsString);
- }
- private static void findPath(int row, int col) {
- if (!isInBounds(row, col)) {
- return;
- }
- currentSum += matrix[row][col];
- currentPath.add(matrix[row][col]);
- if (row == 0 && col == 0) {
- results.putIfAbsent(currentSum, new ArrayList<>(currentPath));
- }
- findPath(row - 1, col);
- findPath(row, col - 1);
- currentSum -= matrix[row][col];
- currentPath.remove(currentPath.size() - 1);
- }
- private static boolean isInBounds(int row, int col) {
- return row >= 0 && col >=0;
- }
- private static int[][] createMatrix(int rows, Scanner scanner) {
- int[][] matrix = new int[rows][];
- for (int i = 0; i < rows; i++) {
- int[] arr = Arrays.stream(scanner.nextLine().split("\\s+"))
- .mapToInt(Integer::parseInt)
- .toArray();
- matrix[i] = arr;
- }
- return matrix;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment