Skip to content

Instantly share code, notes, and snippets.

@cc2011
Created August 26, 2017 06:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cc2011/f82327e3ca64a5bb5efbc218538531bd to your computer and use it in GitHub Desktop.
Save cc2011/f82327e3ca64a5bb5efbc218538531bd to your computer and use it in GitHub Desktop.
public boolean canCross(int[] stones) {
// Write your code here
HashMap<Integer, HashSet<Integer>> dp =
new HashMap<Integer, HashSet<Integer>>(stones.length);
for (int i = 0; i < stones.length; i++) {
dp.put(stones[i], new HashSet<Integer>() );
}
dp.get(0).add(0);
for (int i = 0; i < stones.length - 1; ++i) {
int stone = stones[i];
for (int k : dp.get(stone)) {
// k - 1
if (k - 1 > 0 && dp.containsKey(stone + k - 1))
dp.get(stone + k - 1).add(k - 1);
// k
if (dp.containsKey(stone + k))
dp.get(stone + k).add(k);
// k + 1
if (dp.containsKey(stone + k + 1))
dp.get(stone + k + 1).add(k + 1);
}
}
return !dp.get(stones[stones.length - 1]).isEmpty();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment