python - how to make my maze function print out the solution -
i working on maze solution problem. after code can find goal, not let python print out list of solution. it's required homework.
can me? learned python 3 weeks. want print out every step python goes toward final goal. here code:
def mazedetector(row,col): c= m[row][col] solution=[] if c =="w": print "wall here: "+ str(row)+ ","+ str(col) return false elif c =="v": print "visited: " + str(row)+ ","+ str(col) return false elif c=="f": print "found: "+ str(row)+ ","+ str(col) print solution return true print "visiting:"+ str(row)+ ","+ str(col) solution.append((row,col),) m[row][col]=="v" if (col>0 , mazedetector(row,col-1)): return true elif (row< len(m)-1 , mazedetector(row+1,col)): return true elif (row>0 , mazedetector(row-1, col)): return true elif (col<=len(m)-1 , mazedetector(row, col+1)): return true return false mazedetector(1,5)
and here maze, w
means wall, p
means place go, s
means start, f
means final:
[['w', 'p', 'p', 'w', 'w', 'w'], ['w', 'w', 'p', 'w', 'p', 's'], ['w', 'w', 'p', 'w', 'p', 'w'], ['p', 'p', 'p', 'p', 'p', 'w'], ['f', 'w', 'p', 'w', 'w', 'w'], ['w', 'p', 'p', 'p', 'p', 'w']]
you have pass solution function , not create each time:
def mazedetector(row,col, solution): c= m[row][col] solution.append((row, col)) if c =="w": print "wall here: "+ str(row)+ ","+ str(col) return false elif c =="v": print "visited: " + str(row)+ ","+ str(col) return false elif c=="f": print "found: "+ str(row)+ ","+ str(col) print solution return true print "visiting:"+ str(row)+ ","+ str(col) m[row][col]=="v" if (col>0 , mazedetector(row,col-1, list(solution))): return true elif (row< len(m)-1 , mazedetector(row+1,col, list(solution))): return true elif (row>0 , mazedetector(row-1, col, list(solution))): return true elif (col<=len(m)-1 , mazedetector(row, col+1, list(solution))): return true return false mazedetector(1,5, [])
here's code returns path if exists
def mazedetector(row, col, solution): solution.append((row, col)) if m[row][col] == "f": return true, solution m[row][col] = "v" neighbors = [(row, col - 1), (row + 1, col), (row - 1, col), (row, col + 1)] neighbors = filter(lambda (r, c): r >= 0 , c >= 0 , r < len(m) , c < len(m) , m[r][c] not in ("v", "w"), neighbors) r, c in neighbors: t, sol = mazedetector(r, c, list(solution)) if t: return true, sol return false, [] print mazedetector(1, 5, [])[1]
Comments
Post a Comment