python迷宫问题_Python 练习题:走迷宫

听过部分Python程序员说,不用学递归。黄哥觉得是不对的,如果程序员不掌握递归算法

,那是自费武功。下面是走迷宫golang代码,希望有兴趣的朋友,用Python 写一遍,初学者顺便学习一下递归回溯解决迷宫问题。

package main

// 该代码由黄哥Python培训 黄哥所写 咨询qq:1465376564

import (

"fmt"

)

func valid(grid [][]int, row int, column int) bool {

// 验证可以不可以通行

if row >= 0 && row < len(grid) && column >= 0 && column < len(grid[0]) && grid[row][column] == 1 {

return true

}

return false

}

func walk(grid [][]int, x int, y int) bool {

// 递归退出

if x == len(grid)-1 && y == len(grid[0])-1 {

fmt.Println(grid)

return true

}

// 递归部分

if valid(grid, x, y) {

grid[x][y] = 2

if !walk(grid, x, y+1) {

// 回溯到原位置

grid[x][y] = 1

} else if !walk(grid, x-1, y) {

// 回溯到原位置

grid[x][y] = 1

} else if !walk(grid, x, y-1) {

// 回溯到原位置

grid[x][y] = 1

} else if !walk(grid, x+1, y) {

// 回溯到原位置

grid[x][y] = 1

} else {

return false

}

}

return true

}

func main() {

// 迷宫: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))

}

216小时学会Python

值乎答疑。值乎 - 说点儿有用的

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用OpenCV和Python来解决迷宫问题,可以使用图像处理和径搜索算法。以下是一个基本的实现示例: 1. 导入必要的库: ```python import cv2 import numpy as np ``` 2. 加载迷宫图像并进行预处理: ```python maze = cv2.imread('maze_image.jpg', 0) ret, thresh = cv2.threshold(maze, 127, 255, cv2.THRESH_BINARY) ``` 3. 定义起点和终点坐标: ```python start = (50, 50) # 起点坐标 end = (400, 400) # 终点坐标 ``` 4. 定义可行走方向和移动步长: ```python directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] # 上下左右四个方向 step_size = 10 # 移动步长 ``` 5. 创建径搜索函数: ```python def search_path(current_pos): if current_pos == end: return True for direction in directions: next_pos = (current_pos[0] + direction[0] * step_size, current_pos[1] + direction[1] * step_size) if is_valid_move(next_pos): if search_path(next_pos): return True return False ``` 6. 创建检查移动是否有效的函数: ```python def is_valid_move(pos): if pos[0] < 0 or pos[0] >= maze.shape[0] or pos[1] < 0 or pos[1] >= maze.shape[1]: return False if thresh[pos[0], pos[1]] == 0: return False return True ``` 7. 调用径搜索函数并显示结果: ```python result = search_path(start) if result: print("找到了最短径!") else: print("无法找到最短径!") cv2.imshow("Maze", maze) cv2.waitKey(0) cv2.destroyAllWindows() ``` 这是一个简单的迷宫问题解决示例,它使用OpenCV加载和处理图像,并使用递归径搜索算法来查找起点到终点的最短径。根据具体的迷宫图像和需求,可能需要进行适当的调整和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值