Python 2.X + 3.X:335个字符
打高尔夫球:
def f(n):
x,y=0,0
z=lambda x,y:y<len(n)and x<len(n[0])and n[x][y]!=1
while not z(x,y):
y+=1
if y==len(n):
y=0
x+=1
if x==len(n[0]):
return False
t=set([(x,y)])
v=set()
while t:
(x,y)=t.pop()
v|=set([(x,y)])
if z(x+1,y):
t|=set([(x+1, y)])
if z(x,y+1):
t|=set([(x, y+1)])
return len(v)+sum(map(sum,n))==len(n)*len(n[0])
取消高尔夫:
def f(n):
"""In the following filed, starting from a 0: is it possible to
get to every other 0?
>>> f([[0,0,0,0,0],\
[0,1,0,0,0],\
[0,1,1,1,1],\
[0,0,0,0,0],\
[0,0,0,1,1]])
True
>>> f([[0,1,0,1,0],\
[0,1,1,0,0],\
[0,0,0,0,0],\
[0,0,0,1,0],\
[1,1,1,1,0]])
False
>>> f([[1,1,1,1,1],\
[1,1,1,1,1],\
[1,1,1,1,1],\
[1,1,1,1,1],\
[1,1,1,1,1]])
False
>>> f([[1,1,1,1,1],\
[1,1,1,1,1],\
[1,1,1,1,1],\
[1,0,1,1,1],\
[1,1,1,1,1]])
True
>>> f([[1,1,1,1,1],\
[1,1,1,1,1],\
[0,1,1,1,1],\
[1,0,1,1,1],\
[1,1,0,1,1]])
False
>>> f([[1,1,1,1,1],\
[1,1,1,1,1],\
[1,1,1,1,1],\
[1,1,1,1,1],\
[1,1,1,1,0]])
True
"""
x, y = 0,0
isValid = lambda x,y: y<len(n) and x<len(n[0]) and n[x][y] != 1
for i in range(len(n)*len(n[0])):
x = i%len(n)
y = i/len(n)
if isValid(x,y):
break
while not isValid(x,y):
y += 1
if y == len(n):
y = 0
x += 1
if x == len(n[0]):
return False # Problem is not clearly defined here
toGo=set([(x,y)])
visited=set()
while toGo:
(x,y) = toGo.pop()
visited |= set([(x,y)])
if isValid(x+1,y):
toGo |= set([(x+1, y)])
if isValid(x,y+1):
toGo |= set([(x, y+1)])
return len(visited)+sum(map(sum,n)) == len(n)*len(n[0])
if __name__ == "__main__":
import doctest
doctest.testmod()