- 68
- 0
想要输出所有可能的路线,但是结果只输出一种路线,想了很久没想明白 Orz
以下是源码:
//ma是迷宫
//mb用来标记走过的路mb.fill(0);
//0表示空地,可通行
//1表示障碍物,走不动
//目的地在(x0,y0)
//position=[]
//存放的是现在的位置
//direction=[[-1,0],[0,-1],[1,0],[0,1]];
//destination=[x0,y0];
let ma = [[0, 0, 1, 0],
[0, 0, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 0],
[0, 0, 0, 1]];
let mb = [[1, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]];
let position = new Array(15);
position[0] = [0, 0];
let direction = [[-1, 0], [0, -1], [1, 0], [0, 1]];
let destination = [3, 2];
function maze(step) {
//结束条件是抵达目的地
if (position[step][0] === destination[0] && position[step][1] === destination[1]) {
console.log(position);
return;
}
for (let i = 0; i < 4; i++) {
let new_x = position[step][0] + direction[i][0];
let new_y = position[step][1] + direction[i][1];
if (new_x < 0 || new_x > 4 || new_y < 0 || new_y > 3) {
continue;
}
if (ma[new_x][new_y] === 0 && mb[new_x][new_y] === 0) {
position[step + 1] = [new_x, new_y];
mb[new_x][new_y] = 1;
maze(step + 1);
mb[new_x][new_y] = 0;
}
}
return;
}
maze(0); - 共 0 条
- 全部回答
-
无就将法 普通会员 1楼
深度优先搜索(DFS)是一种用于寻找图中所有可能路径的算法。在Python中,我们可以使用递归的方式来实现深度优先搜索。下面是一个简单的例子,用于找出从起点到指定位置的所有路径:
python def dfs(graph, start, end): if start == end: print("Path found!") return for neighbor in graph[start]: if neighbor == end: print("Path found!") return dfs(graph, neighbor, end)在这个例子中,
graph是一个字典,其中键是节点,值是一个列表,包含了从当前节点到该节点的所有邻居节点。start和end是你想要搜索的节点。如果你想要打印出所有路径,你可以稍微修改一下上面的代码:
python def dfs(graph, start, end): print("Path found!") print("1 ->", start) for neighbor in graph[start]: if neighbor == end: print("Path found!") print("2 ->", neighbor) print("3 ->", end) return dfs(graph, neighbor, end)这个版本的代码会打印出从起点到指定位置的所有路径,以及路径的编号。你可以根据需要修改输出格式。
- 扫一扫访问手机版
回答动态

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器更新之后。服务器里面有部分玩家要重新创建角色是怎么回事啊?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题函数计算不同地域的是不能用内网吧?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题ARMS可以创建多个应用嘛?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题在ARMS如何申请加入公测呀?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题前端小程序接入这个arms具体是如何接入监控的,这个init方法在哪里进行添加?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器刚到期,是不是就不能再导出存档了呢?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器的游戏版本不兼容 尝试更新怎么解决?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器服务器升级以后 就链接不上了,怎么办?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器转移以后服务器进不去了,怎么解决?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器修改参数后游戏进入不了,是什么情况?预计能赚取 0积分收益
- 回到顶部
- 回到顶部
