Advertisement
Guest User

Untitled

a guest
Dec 5th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1.     public boolean canCross(int[] stones) {
  2.         assert(stones != null);
  3.         assert (stones.length > 0);
  4.  
  5.         // BFS
  6.         //Queue<Integer> frontier = new LinkedBlockingQueue<>();
  7.  
  8.         // DFS
  9.         Stack<Integer> frontier = new Stack<>();
  10.         Set<Integer> visited = new HashSet<>();
  11.         Set<Integer> stoneSet = Arrays.stream(stones).boxed().collect(Collectors.toSet());
  12.  
  13.         int targetStone = stones[stones.length - 1];
  14.  
  15.         // start our exploration from the very first stone
  16.         frontier.add(stones[0]);
  17.  
  18.         while (!frontier.isEmpty()) {
  19.  
  20.             // take the next stone from the frontier
  21.             int currentStone = frontier.pop();
  22.             visited.add(currentStone);
  23.  
  24.             // end of the route
  25.             if (currentStone == targetStone) {
  26.                 return true;
  27.             }
  28.  
  29.             // expand the current state into frontier
  30.             for (Integer step : STEPS) {
  31.                 int next = currentStone + step;
  32.                 if (stoneSet.contains(next)) {
  33.                     if (!frontier.contains(next) &&
  34.                             !visited.contains(next)) {
  35.                         frontier.add(next);
  36.                     }
  37.                 }
  38.             }
  39.         }
  40.  
  41.         return false;
  42.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement