403. Frog Jump

65 篇文章 0 订阅
15 篇文章 0 订阅

 

A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.

Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit.

If the frog's last jump was k units, then its next jump must be either k - 1, k, or k + 1 units. Note that the frog can only jump in the forward direction.

Note:

  • The number of stones is ≥ 2 and is < 1,100.
  • Each stone's position will be a non-negative integer < 231.
  • The first stone's position is always 0.

 

Example 1:

[0,1,3,5,6,8,12,17]

There are a total of 8 stones.
The first stone at the 0th unit, second stone at the 1st unit,
third stone at the 3rd unit, and so on...
The last stone at the 17th unit.

Return true. The frog can jump to the last stone by jumping 
1 unit to the 2nd stone, then 2 units to the 3rd stone, then 
2 units to the 4th stone, then 3 units to the 6th stone, 
4 units to the 7th stone, and 5 units to the 8th stone.

 

Example 2:

[0,1,2,3,4,8,9,11]

Return false. There is no way to jump to the last stone as 
the gap between the 5th and 6th stone is too large.

 

思路:最开始用BFS超时,想到用DFS的话,可以先遍历到底,可能会先return,或者可以先收集一遍路上的信息,这样可能可以做一些pruning,但是也TLE,但是修改了一下DFS的顺序,并在DFS之前加一个预判就可以AC,可能是这种方法比较fit OJ 上的case吧,

 

 

package l403;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;

// BFS
public class BFS {
    public boolean canCross(int[] stones) {
    	if(stones.length<2 || stones[1]!=1)	return false;
    	if(stones.length == 2)	return true;
    	int target = stones[stones.length-1];
    	
    	Set<Integer> s = new HashSet<Integer>();
    	for(int i : stones)	s.add(i);
        Queue<int[]> q = new LinkedList<int[]>();
        Queue<int[]> qq = new LinkedList<int[]>();
        q.add(new int[]{1, 1});
        
        while(!q.isEmpty()) {
        	while(!q.isEmpty()) {
        		int[] a = q.remove();
        		int next = a[0]+a[1];
        		
        		if(a[1]>1 && next-1 <= target && s.contains(next-1))	{
        			if(next-1 == target)	return true;
        			qq.add(new int[]{next-1, a[1]-1});
        		}
        		
        		if(next <= target && s.contains(next)) {
        			if(next == target)		return true;
        			qq.add(new int[]{next, a[1]});
        		}
        		
        		if(next+1 <= target && s.contains(next+1))	{
        			if(next+1 == target)	return true;
        			qq.add(new int[]{next+1, a[1]+1});
        		}
        	}
        	q = qq;
        	qq = new LinkedList<int[]>();
        }
        
        return false;
    }
}

 

 

 

 

 

 

package l403;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

// DFS
public class DFS {
    public boolean canCross(int[] stones) {
    	if(stones.length<2 || stones[1]!=1)	return false;
    	if(stones.length == 2)	return true;
    	Map<Integer, Set<Integer>> ll = new HashMap<Integer, Set<Integer>>();
    	for(int i=0; i<stones.length; i++) {
    		if (i > 3 && stones[i] > stones[i - 1] * 2) return false;
    		Set<Integer> l = new HashSet<Integer>();
    		for(int j=i+1; j<stones.length; j++)	l.add(stones[j]);
    		ll.put(stones[i], l);
    	}
        
    	return dfs(stones[stones.length-1], 1, 1, ll);
    }
    
	private boolean dfs(int target, int pos, int preStep, Map<Integer, Set<Integer>> ll) {
		if(target == pos)	return true;
		if(target < pos)	return false;
		
		Set<Integer> l = ll.get(pos);
		if(l == null)		return false;
		
		if(l.contains(pos+preStep+1)) {
			l.remove(pos+preStep+1);
			if(dfs(target, pos+preStep+1, preStep+1, ll))	return true;
		}
		
		if(l.contains(pos+preStep)) {
			l.remove(pos+preStep);
			if(dfs(target, pos+preStep, preStep, ll))	return true;
		}
		
		if(preStep>1 && l.contains(pos+preStep-1)) {
			l.remove(pos+preStep-1);
			if(dfs(target, pos+preStep-1, preStep-1, ll))	return true;
		}
		
		return false;
	}
}

 

 

 

 

 

修改DFS的顺序后AC的版本,感觉OJ上的case不太好

 

package l403;

import java.util.HashSet;
import java.util.Set;

// DFS
public class Solution {
    public boolean canCross(int[] stones) {
    	if(stones.length<2 || stones[1]!=1)	return false;
    	if(stones.length == 2)	return true;
    	Set<Integer> ll = new HashSet<Integer>();
    	for(int i=0; i<stones.length; i++) {
    		if (i > 3 && stones[i] > stones[i - 1] * 2) return false;
    		ll.add(stones[i]);
    	}
        
    	return dfs(stones[stones.length-1], 1, 1, ll);
    }
    
	private boolean dfs(int target, int pos, int preStep, Set<Integer> l) {
		int next = pos+preStep;
		if(Math.abs(next-target) <= 1)	return true;
		
		if(l.contains(pos+preStep+1)) {
			if(dfs(target, pos+preStep+1, preStep+1, l))	return true;
		}
		
		if(l.contains(pos+preStep)) {
			if(dfs(target, pos+preStep, preStep, l))	return true;
		}
		
		if(preStep>1 && l.contains(pos+preStep-1)) {
			if(dfs(target, pos+preStep-1, preStep-1, l))	return true;
		}
		
		return false;
	}
}

 

或者:对每个stone,维护一个set表示在当前stone能采取的step

然后再求stone i的时候遍历一下之前的stone,看之前的stone里面有没有那么一个step可以转到当前stone

 

Use map to represent a mapping from the stone (not index) to the steps that can be taken from this stone.

so this will be

[0,1,3,5,6,8,12,17]

{17=[], 0=[1], 1=[1, 2], 3=[1, 2, 3], 5=[1, 2, 3], 6=[1, 2, 3, 4], 8=[1, 2, 3, 4], 12=[3, 4, 5]}

Notice that no need to calculate the last stone.

On each step, we look if any other stone can be reached from it, if so, we update that stone's steps by adding step, step + 1, step - 1. If we can reach the final stone, we return true. No need to calculate to the last stone.

class Solution:
    def canCross(self, stones):
        """
        :type stones: List[int]
        :rtype: bool
        """
        s = set()
        s.add(1)
        d = {0:s}
        for i in range(1, len(stones)):
            s = set()
            for k in d:
                step = stones[i]-k
                if step in d[k]:
                    s.add(step)
                    s.add(step+1)
                    s.add(step-1)
            d[stones[i]] = s
        
        return len(d[stones[-1]])!=0
    
s = Solution()
print(s.canCross([0,1,3,5,6,8,12,17]))
print(s.canCross([0,1,2,3,4,8,9,11]))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值