|
| 1 | +class Solution { |
| 2 | + boolean[][] dp; |
| 3 | + public boolean canCross(int[] stones) { |
| 4 | + |
| 5 | + if(stones[1]!=1) return false; |
| 6 | + |
| 7 | + int n = stones.length; |
| 8 | + dp = new boolean[n][n]; |
| 9 | + return helper(stones,0,1); |
| 10 | + } |
| 11 | + |
| 12 | + boolean helper(int[] stones,int lastIndex,int currentIndex){ |
| 13 | + if(currentIndex == stones.length - 1){ |
| 14 | + return true; |
| 15 | + } |
| 16 | + |
| 17 | + if(dp[lastIndex][currentIndex]) return false; |
| 18 | + |
| 19 | + int lastJump = stones[currentIndex] - stones[lastIndex]; |
| 20 | + |
| 21 | + int nextIndex = currentIndex + 1; |
| 22 | + |
| 23 | + while(nextIndex<stones.length && stones[nextIndex]<= stones[currentIndex] + lastJump + 1){ |
| 24 | + int nextJump = stones[nextIndex] - stones[currentIndex]; |
| 25 | + int jump = nextJump - lastJump; |
| 26 | + |
| 27 | + if(jump>=-1 && jump<=1){ |
| 28 | + if(helper(stones,currentIndex,nextIndex)){ |
| 29 | + return true; |
| 30 | + } |
| 31 | + } |
| 32 | + nextIndex++; |
| 33 | + } |
| 34 | + |
| 35 | + dp[lastIndex][currentIndex] = true; |
| 36 | + |
| 37 | + return false; |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | + |
| 42 | +class Solution { |
| 43 | + Map<String,Boolean> dp =null; |
| 44 | + public boolean canCross(int[] stones) { |
| 45 | + if(stones[1]!=1) return false; |
| 46 | + dp = new HashMap<>(); |
| 47 | + return helper(stones,1,1); |
| 48 | + } |
| 49 | + |
| 50 | + boolean helper(int[] stones, int index,int jump){ |
| 51 | + if(index == stones.length - 1){ |
| 52 | + return true; |
| 53 | + } |
| 54 | + if(dp.containsKey(index+"-"+jump)) return dp.get(index+"-"+jump); |
| 55 | + boolean ans = false; |
| 56 | + for(int j = Math.max(1,jump - 1); j<=jump+1;j++){ |
| 57 | + if(j==0) continue; |
| 58 | + int newStone = stones[index] + j; |
| 59 | + int indexNew = exists(stones,newStone); |
| 60 | + if(indexNew!=-1){ |
| 61 | + ans |= helper(stones,indexNew,j); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + dp.put(index+"-"+jump,ans); |
| 66 | + |
| 67 | + return ans; |
| 68 | + } |
| 69 | + |
| 70 | + int exists(int[] stone,int target){ |
| 71 | + int left=0,right = stone.length-1; |
| 72 | + while(left<=right){ |
| 73 | + int mid = left + (right - left)/2; |
| 74 | + if(stone[mid]==target) { |
| 75 | + return mid; |
| 76 | + } |
| 77 | + else if(stone[mid]>target) right = mid-1; |
| 78 | + else left = mid+1; |
| 79 | + } |
| 80 | + |
| 81 | + return -1; |
| 82 | + } |
| 83 | +} |
0 commit comments