14.猫捉老鼠
http://acm.fzu.edu.cn/problem.php?pid=1019
难点主要在于如何判断是否永远追不上。
思路:若某一时刻猫和老鼠同时处在它们之前已经处过的状态,则二者永远不会相遇。
import sys
def cat_mouse(room):
times=0
catch_up=True
for i in range(0,10):
for j in range(0,10):
if room[i][j]=='m':
mouse_start=[i,j]
room[i][j]='.'
if room[i][j]=='c':
cat_start=[i,j]
room[i][j]='.'
cat=Animal(cat_start,room)
mouse=Animal(mouse_start,room)
path=[] # 保存猫与老鼠同一时刻各自所处的位置和状态
while cat.location!=mouse.location:
times+=1
cat.move()
mouse.move()
# 特别注意若无静态化处理,坐标值会随之改变
situation=[['c',str(cat.location),cat.direction],
['m',str(mouse.location),mouse.direction]]
if not situation in path:
path.append(situation)
else:
catch_up=False
break
if catch_up:
print(times)
else:
print(0)
class Animal():
def __init__(self,location,room):
self.direction='up'
self.location=location
self.room=room
def move(self):
if self.direction=='up':
next_pos=[self.location[0]-1,self.location[1]]
if self.__pos_in_room(next_pos) and self.__next_situation(next_pos)=='.':
self.location[0]-=1
else:
self.direction='right'
elif self.direction=='right':
next_pos=[self.location[0],self.location[1]+1]
if self.__pos_in_room(next_pos) and self.__next_situation(next_pos)=='.':
self.location[1]+=1
else:
self.direction='down'
elif self.direction=='down':
next_pos=[self.location[0]+1,self.location[1]]
if self.__pos_in_room(next_pos) and self.__next_situation(next_pos)=='.':
self.location[0]+=1
else:
self.direction='left'
else:
next_pos=[self.location[0],self.location[1]-1]
if self.__pos_in_room(next_pos) and self.__next_situation(next_pos)=='.':
self.location[1]-=1
else:
self.direction='up'
def __pos_in_room(self,position):
if (position[0] in range(0,10)) and (position[1] in range(0,10)):
return True
else:
return False
def __next_situation(self,position):
return room[position[0]][position[1]]
if __name__=='__main__':
lines=sys.stdin.readlines()
if lines:
groups=int(lines[0].rstrip())
line_in_group=0
room=[]
for line in lines[1:]:
if line_in_group==10:
line_in_group=0
else:
line_in_group+=1
room.append([x for x in list(line.rstrip())])
if line_in_group==10:
cat_mouse(room)