Matlab 广度优先搜索求解迷宫问题

function BFS_Maze(maze)

% maze:是迷宫矩阵,其中0表示可以去走的路
%                     1表示障碍
%                     2表示入口
%                     3表示出径
%                     5表示路径
%             0 2 0 0 1
%             0 1 1 0 1
%             0 1 3 0 1
%             0 1 0 0 1

% copyright: qbb 2013-3-12
if nargin == 0
    maze = [0 2 0 0 1
        0 1 1 0 1
        0 1 3 0 1
        0 1 0 0 1];
end
mazecopy = maze;
% 定义四个方向
directions = kron(eye(2),[-1,1]);
% 数组存储解的情况,I, J ,Pre
remark = zeros(100,3);
[I,J] = find(maze == 2);% 找到起点
remark(1,:) = [I,J,-1];
count = 2;
search(1);
sol = remark(count-1,:);
while(sol(end,3) > 0)
    sol = [sol;remark(sol(end,3),:)];
end
mazecopy(sub2ind(size(maze), sol(2:end-1,1), sol(2:end-1,2))) = 5;
disp(mazecopy);
disp(sol);
    function search(front)
        x = remark(front,1);
        y = remark(front,2);        
        for i = 1 : 4
            if cango(x + directions(1,i),y + directions(2,i))
                remark(count,1) = x + directions(1,i);
                remark(count,2) = y + directions(2,i);
                remark(count,3) = front;
                count = count + 1;
                if maze(x + directions(1,i),y + directions(2,i)) ~= 3
                    maze(x + directions(1,i),y + directions(2,i)) = 5;% 记录下来
                else
                    return;
                end
                
            end
        end
        search(front + 1);
    end
% 该函数判断该点是否可以经过
    function z = cango(x,y)
        % 用try来判断边界
        z = true;
        try
            if ismember(maze(x,y),[1,2,5])% 路障或者已经走过
                z = false;
            end
        catch
            z = false; % 边界
        end
    end
end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值