Breadth First Search on Labyrinth in Matlab
本问题已经有最佳答案,请猛点这里访问。
我正在尝试实现一个广度优先的算法,它解决了一个迷宫。作为输入,我有一个n*m的二进制矩阵,其中"1"代表障碍物/墙壁,"0"代表路径/自由单元。
我确实知道算法通常是如何工作的,但是我正在努力学习如何在matlab中存储和处理信息。所以基本上,我从我的起始单元格开始,检查它的所有直接邻居是否有障碍。如果它们是自由的,我将它们标记为一个潜在的路径,然后对所有这些单元格再次执行相同的递归操作。
但我只是不知道如何存储信息,所以最终我只有一条路。有什么想法吗?
这是一个通过深度优先搜索在无方向图中搜索连接组件的函数。BFS应该更容易编码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | function comp = findNodeComponentDFS(G, node) %Find a connected component of the given node in the unoriented graph. Use %Deep first search (Cormen, Rivest, Leiserson) %G - connectivity matrix %node - given node %comp - contain the numbers of all nodes in the found connected component %except the node itself N = length(G); white = ones(1,N);%unexamined vertices grey = zeros(1,N);%vertices that are currently examining but with not all edges have been examined yet black = zeros(1,N);%vertices with all the edges have been examined prev = zeros(1,N); current = node; stop=false; while (~stop) grey(current) = 1; white(current) = 0; next = find(G(current,:) & white,1); if (isempty(next)) black(current) = 1; if (prev(current)==0) stop = true; else current = prev(current);%back to previous vertice end else prev(next) = current; current = next; end end comp = find(black); |
您可以像在星体寻路算法中那样使用打开和关闭的列表。检查所有邻居,如果邻居不是障碍物,则将其列入开放列表。检查所有邻居和成本最低的邻居,将其列入封闭名单。最后,在封闭列表中找到了最佳路径。基本上是这样的……