Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public boolean canCross(int[] stones) {
- assert(stones != null);
- assert (stones.length > 0);
- // BFS
- //Queue<Integer> frontier = new LinkedBlockingQueue<>();
- // DFS
- Stack<Integer> frontier = new Stack<>();
- Set<Integer> visited = new HashSet<>();
- Set<Integer> stoneSet = Arrays.stream(stones).boxed().collect(Collectors.toSet());
- int targetStone = stones[stones.length - 1];
- // start our exploration from the very first stone
- frontier.add(stones[0]);
- while (!frontier.isEmpty()) {
- // take the next stone from the frontier
- int currentStone = frontier.pop();
- visited.add(currentStone);
- // end of the route
- if (currentStone == targetStone) {
- return true;
- }
- // expand the current state into frontier
- for (Integer step : STEPS) {
- int next = currentStone + step;
- if (stoneSet.contains(next)) {
- if (!frontier.contains(next) &&
- !visited.contains(next)) {
- frontier.add(next);
- }
- }
- }
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement