Advertisement
Guest User

Untitled

a guest
May 19th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.17 KB | None | 0 0
  1. package RecursionHomework;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class ScroogeMcDuck {
  6. public static void main(String[] args) {
  7. Scanner scanner = new Scanner(System.in);
  8. int row = scanner.nextInt();
  9. int col = scanner.nextInt();
  10. int currentRow = 0;
  11. int currentCol = 0;
  12. int[][] labyrinth = new int[row][col];
  13. for (int i = 0; i < row; i++) {
  14. for (int j = 0; j < col; j++) {
  15. int number = scanner.nextInt();
  16. labyrinth[i][j] = number;
  17. if (number == 0) {
  18. currentRow = i;
  19. currentCol = j;
  20. }
  21. }
  22. }
  23. System.out.println(countCoinsRec(labyrinth, currentRow, currentCol));
  24. }
  25.  
  26. private static int countCoinsRec(int[][] labyrinth, int curRow, int curCol) {
  27. char direction = 'n';
  28. int biggestDirection = 0;
  29.  
  30. if (isInRange(labyrinth, curRow ,curCol-1)) {
  31. int left = labyrinth[curRow][curCol-1];
  32. if (biggestDirection < left) {
  33. biggestDirection = left;
  34. direction = 'l';
  35. }
  36. }
  37. if (isInRange(labyrinth, curRow ,curCol+1)) {
  38. int right = labyrinth[curRow][curCol+1];
  39. if (biggestDirection < right) {
  40. biggestDirection = right;
  41. direction = 'r';
  42. }
  43. }
  44. if (isInRange(labyrinth, curRow + 1,curCol)) {
  45. int up = labyrinth[curRow+1][curCol];
  46. if (biggestDirection < up) {
  47. biggestDirection = up;
  48. direction = 'u';
  49. }
  50. }
  51. if (isInRange(labyrinth, curRow - 1,curCol)) {
  52. int down = labyrinth[curRow - 1][curCol];
  53. if (biggestDirection < down) {
  54. direction = 'd';
  55. }
  56. }
  57. if (labyrinth[curRow][curCol] != 0) {
  58. labyrinth[curRow][curCol] -= 1;
  59. switch (direction) {
  60. case 'l':
  61. return countCoinsRec(labyrinth, curRow ,curCol-1) + 1;
  62. case 'r':
  63. return countCoinsRec(labyrinth, curRow ,curCol+1) + 1;
  64. case 'u':
  65. return countCoinsRec(labyrinth, curRow+1 ,curCol) + 1;
  66. case 'd':
  67. return countCoinsRec(labyrinth, curRow-1 ,curCol) + 1;
  68. default:
  69. return 1;
  70. }
  71. } else {
  72. switch (direction) {
  73. case 'l':
  74. return countCoinsRec(labyrinth, curRow ,curCol-1);
  75. case 'r':
  76. return countCoinsRec(labyrinth, curRow ,curCol+1);
  77. case 'u':
  78. return countCoinsRec(labyrinth, curRow+1 ,curCol);
  79. case 'd':
  80. return countCoinsRec(labyrinth, curRow-1 ,curCol);
  81. default:
  82. return 0;
  83. }
  84. }
  85. }
  86.  
  87. private static boolean isInRange(int[][] labyrinth, int row, int col) {
  88. return row<labyrinth.length && row>=0 && col < labyrinth[0].length && col >= 0;
  89. }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement