fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main(String[] args) {
  11. final List<Integer> path = solve(3, 6, 4, 1, 3, 4, 2, 5, 3, 0);
  12.  
  13. for (Integer i : path) {
  14. System.out.print(i + " -> ");
  15. }
  16. System.out.println("DONE");
  17. }
  18.  
  19. static List<Integer> solve(int... a) {
  20. //Value in each element is the index, from where we can come here
  21. int[] path = new int[a.length];
  22. Arrays.fill(path, -1); //No index is accessible yet
  23.  
  24. //Queue of positions that were visited from somewhere, but nothing was tried to be
  25. //visited from them. At the beginning, 0 is in the list, because it's starting point.
  26. //Then, if we visit index 3, it is added to this list for later processing.
  27. Queue<Integer> posQueue = new LinkedList<>();
  28. posQueue.add(0);
  29. path[0] = 0; //0 index is accessible from itself, this is starting position
  30.  
  31. while (!posQueue.isEmpty()) {
  32. int pos = posQueue.remove();
  33. int prPos = pos - a[pos];
  34. int nxPos = pos + a[pos];
  35. if (prPos >= 0 && path[prPos] == -1) {
  36. path[prPos] = pos;
  37. posQueue.add(prPos);
  38. }
  39. if (nxPos < a.length && path[nxPos] == -1) {
  40. path[nxPos] = pos;
  41. posQueue.add(nxPos);
  42. }
  43.  
  44. if (path[a.length-1] != -1) {
  45. break;
  46. }
  47. }
  48.  
  49. if (path[a.length-1] == -1) {
  50. return null;
  51. }
  52.  
  53. //Collect the path
  54. List<Integer> result = new ArrayList<>();
  55. int idx = a.length-1;
  56. while (idx != 0) {
  57. result.add(0, idx);
  58. idx = path[idx];
  59. }
  60. result.add(0, 0);
  61. return result;
  62. }
  63. }
Success #stdin #stdout 0.04s 711168KB
stdin
Standard input is empty
stdout
0 -> 3 -> 2 -> 6 -> 8 -> 5 -> 9 -> DONE