题解 | #迷宫问题#
迷宫问题
http://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
根据该题学到了一个知识点: list通过等号复制(list2=list1)赋值的对象是指针,新旧列表相互关联; list通过copy复制(list2=list1.copy())赋值对象是元素,新旧列表不相互影响 代码如下:
while True:
try:
def one_jump(mymap,pathset,row,col):
n=len(pathset)
for j in range(n-1,-1,-1):
path=pathset[j]
curpos=path[-1]
#print(f'curpos={curpos}')
availablepos=list()
if (curpos[1]-1>-1) and (mymap[curpos[0]][curpos[1]-1]=='0'):
#向左走
mymap[curpos[0]][curpos[1]]='1'
availablepos.append([curpos[0],curpos[1]-1])
if (curpos[1]+1<col) and (mymap[curpos[0]][curpos[1]+1]=='0'):
#向右
mymap[curpos[0]][curpos[1]]='1'
availablepos.append([curpos[0],curpos[1]+1])
if (curpos[0]-1>-1) and (mymap[curpos[0]-1][curpos[1]]=='0'):
#向上
mymap[curpos[0]][curpos[1]]='1'
availablepos.append([curpos[0]-1,curpos[1]])
if (curpos[0]+1<row) and (mymap[curpos[0]+1][curpos[1]]=='0'):
#向下
mymap[curpos[0]][curpos[1]]='1'
availablepos.append([curpos[0]+1,curpos[1]])
#print(f'availablepos={availablepos}')
if len(availablepos)==0:
pathset.pop(j)
continue
oldpath=path.copy()
#print(f'oldpath={oldpath}')
for i in range(len(availablepos)):
if i==0:
path.append(availablepos[i])
else:
newpath=oldpath.copy()
#print(f'oldpath={oldpath}')
newpath.append(availablepos[i])
pathset.append(newpath)
#print(f'pathsets={pathset}')
return pathset
def findpath(row,col):
mymap=list()
for i in range(row):
rown=input().split(' ')
mymap.append(rown)
curpos=[0,0]
pathsets=list()
path=list()
path.append(curpos)
pathsets.append(path)
pathsets=one_jump(mymap, pathsets, row, col)
#print(pathsets)
while True:
pathsets=one_jump(mymap, pathsets, row, col)
#print(pathsets)
isfind=False
for path in pathsets:
if path[-1]==[row-1,col-1]:
isfind=True
for k in path:
print('({0},{1})'.format(k[0],k[1]))
break
if isfind: break
n=input()
n=n.split(' ')
row=int(n[0])
col=int(n[1])
findpath(row, col)
except:
break