在Matlab中使用Labyrinth进行广度优先搜索

时间:2014-12-05 16:23:15

标签: algorithm matlab matrix breadth-first-search

我正在尝试实现广度优先算法,它解决了迷宫问题。作为输入,我有一个n * m二进制矩阵,其中'1'代表障碍/墙,'0'代表路径/空闲单元。

我确实知道算法通常如何工作,但我正在努力如何在matlab中存储和处理信息。 所以基本上我从我的起始单元开始,并检查所有它的直接邻居的障碍。如果它们是空闲的,我将它们标记为潜在路径,然后我再次对所有这些单元格进行相同的处理。

但我无法弄清楚如何存储信息,所以最后我只会有一条路径。 有任何想法吗?

2 个答案:

答案 0 :(得分:0)

您可以像使用星形寻路算法一样使用打开和关闭列表。检查所有邻居,如果邻居不是障碍物,请将其放入打开的列表中。检查所有邻居和具有最低成本的邻居,将其放入关闭列表中。最后,您在关闭列表中拥有最佳路径。基本上就是这样......

答案 1 :(得分:0)

这是一个通过深度优先搜索在非定向图中搜索连接组件的功能。 BFS应该更容易编码。

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);