从左上角开始的直升机正向地面下降(为了这个问题,在2D空间中)。它有自动驾驶模式和手动模式。
自动驾驶仪模式表现如下:
它不停地重复这两个步骤,直到它落到地面。手动模式更聪明,即使这需要向上移动或一些熟练的操纵,也会找到通往地面的最佳路径。
你的工作是确定
四个预定义字符中的一个,指示发生了哪一种情况。
在输入中使用0(空)和1(阻塞),在输出中使用1 2 3 4(如上面所示)
0 0 0 0
0 1 0 0
0 0 0 1
1 1 0 0输出:1
0 0 1 0
1 0 0 1
0 0 0 0
0 1 1 0
0 0 0 1输出:2 (直升机将在第四行遇到1,如果在自动驾驶模式下,它可能会在第5行的末尾设置陷阱)
0 0 0 1 0
0 1 1 0 0
0 1 0 0 0
0 0 0 1 0
1 1 1 1 0输出:3 (这需要向上移动,因此自动驾驶仪失败)
1 0 0
0 0 0输出:4
0 0 0 0 1
1 1 1 0 0
1 0 0 1 0
0 1 0 0 0
0 0 1 1 1输出:4
发布于 2016-02-11 06:07:56
我玩得很开心。谢谢!网格的挑战往往是极好的乐趣和有趣的挑战。这假设问题中的“字符”可以是整数。
我认为这里的主要改进之处是:
r的创建->a,h,w{f=->l,s=0,y=[0]{r=w-2<s%w ?w:1,1>s%w ?w:-1,w
v=(l ?r+[-w]:a[s+w]==0?[w]:r).map{|d|a[m=s+d]==0&&!y[m]?m:p}-q=[p]
a[s]>0?q:s/w>h-2?8:v[0]?v.map{|o|f[l,y[o]=o,y]}.flatten-q :r.any?{|i|a[s+i]<1}?p: !0}
g=f[p]
[8,g[0]&&g.all?,g.any?,f[8].any?,!p].index !p}不打高尔夫球(有点过时,但非常接近):
# a is a one-dimensional array of 0s and 1s, h is height, w is width
->a,h,w{
# f recursively walks the array and returns true/false/nil for each path.
# True means we can reach ground.
# False means we are stuck in a local minimum and cannot escape
# Nil means we reached a local dead-end and need to backtrack.
# l: {true=>"manual", false=>"autopilot"}
# s: the position index
# y: an array of booleans - true-ish means we've visited that square before
# (this is to prevent infinite loops, esp in manual mode)
f=->l,s=0,y=[0]{
# d: all the legal deltas from s (maximally, that's [1,-1,w,-w], aka [LRDU])
# r: but the right and left get tricky on the edges, so let's pre-calculate those
# we'll default to "down" if "left" or "right" are illegal
r=[w-2<s%w ?w:1,1>s%w ?w:-1]
# if manual, [LRDU]; if auto, and you can go down, [D]. else, [LR]
d=l ?r+[w,-w]:a[s+w]==0?[w]:r
# v: the legal deltas that you can go to from s (that is, unvisited and unblocked)
v=d.map{|d|a[m=s+d]==0&&!y[m]?m:p}-[p]
a[s]>0 ? [p] # if we're currently blocked, return [nil] (this is only the case when a[0]==1)
: s/w>h-2 ? !p # if we're at the bottom, return true
: v[0] ? # if we have a place to go....
v.map{|o|f[l,y[o]=o,y]}.flatten-[p] # recurse with each step.
# y[o]=o is a neat trick to make y[o] truthy and return o
: r.any?{|i|a[s+i]==0} ? # otherwise, we have nowhere to go. If we could visit left/right, but have already been there
p # this is not a dead-end - return nil to remove this path
: !!p # If we have a true dead-end (auto-mode with a local minimum), false
}
# g is the auto flight
g=f[p]
# finally, choose the first "true" out of:
# 0: always 8. Cuz why not 8?
# 1: there is at least one auto path, and all are truthy
# 2: any auto path is truthy
# 3: any manual path is truthy
# 4: true
[8,g[0]&&g.all?,g.any?,f[!p].any?,!p].index !p
}https://codegolf.stackexchange.com/questions/69929
复制相似问题