defvalid(grid,x,y):ifx>=0andx<len(grid)andy>=0andy<len(grid[0])andgrid[x][y]==1:returnTrueelse:returnFalsedefwalk(grid,x,y):ifx==len(grid)-1andy==len(grid[0])-1:print'success'grid[x][y]=2returnTrueifvalid(grid,x,y):grid[x][y]=2ifwalk(grid,x,y+1)orwalk(grid,x-1,y)orwalk(grid,x,y-1)orwalk(grid,x+1,y):returnTrueelse:grid[x][y]=1returnFalseelse:returnFalsegrid=[[1,1,1,0,1,1,0,0,0,1,1,1,1],[1,0,1,1,1,0,1,1,1,1,0,0,1],[0,0,0,0,1,0,1,0,1,0,1,0,0],[1,1,1,0,1,1,1,0,1,0,1,1,1],[1,0,1,0,0,0,0,1,1,1,0,0,1],[1,0,1,1,1,1,1,1,0,1,1,1,1],[1,0,0,0,0,0,0,0,0,0,0,0,0],[1,1,1,1,1,1,1,1,1,1,1,1,1]]if__name__=='__main__':walk(grid,0,0)foriinrange(len(grid)):print(grid[i])

#!/usr/bin/envpython#-*-coding:utf-8-*-#Createdbyxiaoqin00#迷宫逃亡result=''defmazeValid(x,y,maze):ifx>=0andy>=0andx<len(maze)andy<len(maze)andmaze[x][y]=='O':returnTruereturnFalsedefmazeCracker(x,y,Maze,MazeOut):ifx==int(MazeOut[0])-1andy==int(MazeOut[1])-1:returnTrueifmazeValid(x,y,Maze):Maze[x][y]='X'ifmazeCracker(x+1,y,Maze,MazeOut)ormazeCracker(x-1,y,Maze,MazeOut)ormazeCracker(x,y+1,Maze,MazeOut)ormazeCracker(x,y-1,Maze,MazeOut):returnTrueelse:Maze[x][y]='X'returnFalseelse:returnFalse#readtxtif__name__=='__main__':result=''#从txt文件中读取迷宫参数f=open('C:\\Users\\00\\Desktop\\1.txt','r')mazeLen=[]mazeIn=[]mazeOut=[]maze=[]i=1#将文件中的迷宫参数分类forlineinf:ifline[0].isdigit():i=i%3ifi==1:mazeLen.append(line.strip('\n'))elifi==2:mazeIn.append(line.strip('\n'))else:mazeOut.append(line.strip('\n'))i+=1ifline[0].isalpha():maze.append(line.strip('\n'))count=0Maze=[]MazeTmp=[]foriinrange(len(mazeIn)):mazeIn[i]=mazeIn[i].split()foriinrange(len(mazeOut)):mazeOut[i]=mazeOut[i].split()foriinmazeLen:forjinmaze[0:int(i)]:forkinj:MazeTmp.append(k)Maze.append(MazeTmp)MazeTmp=[]ifmazeCracker(int(mazeIn[count][0])-1,int(mazeIn[count][1])-1,Maze,mazeOut[count]):result+='1'else:result+='0'count+=1Maze=[]printresult

参考的golang代码packagemainimport("fmt")funcvalid(grid[][]int,rowint,columnint)bool{//验证可以不可以通行ifrow>=0&&row<len(grid)&&column>=0&&column<len(grid[0])&&grid[row][column]==1{returntrue}returnfalse}funcwalk(grid[][]int,xint,yint)bool{//递归退出ifx==len(grid)-1&&y==len(grid[0])-1{fmt.Println(grid)returntrue}//递归部分ifvalid(grid,x,y){grid[x][y]=2if!walk(grid,x,y+1){//回溯到原位置grid[x][y]=1}elseif!walk(grid,x-1,y){//回溯到原位置grid[x][y]=1}elseif!walk(grid,x,y-1){//回溯到原位置grid[x][y]=1}elseif!walk(grid,x+1,y){//回溯到原位置grid[x][y]=1}else{returnfalse}}returntrue}funcmain(){//迷宫:1表示通路、0是墙grid:=[][]int{{1,1,1,0,1,1,0,0,0,1,1,1,1},{1,0,1,1,1,0,1,1,1,1,0,0,1},{0,0,0,0,1,0,1,0,1,0,1,0,0},{1,1,1,0,1,1,1,0,1,0,1,1,1},{1,0,1,0,0,0,0,1,1,1,0,0,1},{1,0,1,1,1,1,1,1,0,1,1,1,1},{1,0,0,0,0,0,0,0,0,0,0,0,0},{1,1,1,1,1,1,1,1,1,1,1,1,1},}fmt.Println(walk(grid,0,0))}