Created
June 4, 2013 23:01
-
-
Save st0le/5710371 to your computer and use it in GitHub Desktop.
Minimum Hops
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
def random_array(sz,low=10,high = 100): | |
return map(lambda i:random.randint(low,high),xrange(sz)) | |
R = random_array(50,1,10) | |
print R | |
def minhops_dfs(lst): | |
sz = len(lst) | |
min_hop = [0] * sz | |
def dfs(index,s,hops,min_hop): | |
if index >= sz: | |
if len(min_hop) > s: | |
min_hop[:] = hops | |
#min_hop.extend(hops) | |
elif s > len(min_hop): | |
pass | |
else: | |
hops.append(lst[index]) | |
for i in xrange(1,lst[index] + 1): | |
dfs(index + i, s + 1,hops,min_hop) | |
hops.pop() | |
dfs(0,0,[],min_hop) | |
return len(min_hop) | |
def min_hops_dp(lst): | |
sz = len(lst) | |
min_hops = [0] * sz | |
for l in xrange(sz - 1,-1,-1): | |
if lst[l] + l >= sz: | |
min_hops[l] = 1 | |
else: | |
end = min(lst[l] + l,sz) | |
min_hops[l] = 1 + min(min_hops[l+1:end+1]) | |
return min_hops[0] | |
print minhops_dfs(R) | |
print min_hops_dp(R) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment