Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package RecursionHomework;
- import java.util.Scanner;
- public class ScroogeMcDuck {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int row = scanner.nextInt();
- int col = scanner.nextInt();
- int currentRow = 0;
- int currentCol = 0;
- int[][] labyrinth = new int[row][col];
- for (int i = 0; i < row; i++) {
- for (int j = 0; j < col; j++) {
- int number = scanner.nextInt();
- labyrinth[i][j] = number;
- if (number == 0) {
- currentRow = i;
- currentCol = j;
- }
- }
- }
- System.out.println(countCoinsRec(labyrinth, currentRow, currentCol));
- }
- private static int countCoinsRec(int[][] labyrinth, int curRow, int curCol) {
- char direction = 'n';
- int biggestDirection = 0;
- if (isInRange(labyrinth, curRow ,curCol-1)) {
- int left = labyrinth[curRow][curCol-1];
- if (biggestDirection < left) {
- biggestDirection = left;
- direction = 'l';
- }
- }
- if (isInRange(labyrinth, curRow ,curCol+1)) {
- int right = labyrinth[curRow][curCol+1];
- if (biggestDirection < right) {
- biggestDirection = right;
- direction = 'r';
- }
- }
- if (isInRange(labyrinth, curRow + 1,curCol)) {
- int up = labyrinth[curRow+1][curCol];
- if (biggestDirection < up) {
- biggestDirection = up;
- direction = 'u';
- }
- }
- if (isInRange(labyrinth, curRow - 1,curCol)) {
- int down = labyrinth[curRow - 1][curCol];
- if (biggestDirection < down) {
- direction = 'd';
- }
- }
- if (labyrinth[curRow][curCol] != 0) {
- labyrinth[curRow][curCol] -= 1;
- switch (direction) {
- case 'l':
- return countCoinsRec(labyrinth, curRow ,curCol-1) + 1;
- case 'r':
- return countCoinsRec(labyrinth, curRow ,curCol+1) + 1;
- case 'u':
- return countCoinsRec(labyrinth, curRow+1 ,curCol) + 1;
- case 'd':
- return countCoinsRec(labyrinth, curRow-1 ,curCol) + 1;
- default:
- return 1;
- }
- } else {
- switch (direction) {
- case 'l':
- return countCoinsRec(labyrinth, curRow ,curCol-1);
- case 'r':
- return countCoinsRec(labyrinth, curRow ,curCol+1);
- case 'u':
- return countCoinsRec(labyrinth, curRow+1 ,curCol);
- case 'd':
- return countCoinsRec(labyrinth, curRow-1 ,curCol);
- default:
- return 0;
- }
- }
- }
- private static boolean isInRange(int[][] labyrinth, int row, int col) {
- return row<labyrinth.length && row>=0 && col < labyrinth[0].length && col >= 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement