Matlab 进行迷宫行走游戏求解

Matlab 进行迷宫行走游戏求解

原题用C(C++)写

题目:有一个愚蠢的机器人走进一个w*h的迷宫,迷宫里有空地和陷阱。他想要访问迷宫的每个方格,但是它很笨,只会按照指令的方向走。当机器人不能走的时候,也就是下一步会遇到陷阱、迷宫边界或者访问过的格子,它会向右转90度(顺时针旋转90度,不能访问已经访问过的方格,且在原地只转一次,移动后可获得又一次旋转机会)。请问这个机器人最多可以经过多少个方格。

示意图

在这里插入图片描述
图片题目来自于http://39.106.164.46/problem.php?id=1021&tdsourcetag=s_pcqq_aiomsg

特点

  • 可以生成任何大小的迷宫;
  • 随机确定障碍物的地址;
  • 随机确定初始点的位置、方向

设计思想

1. 边界判别

这一步的主要目的是,将机器人的行走情况分开来讨论

function logic = judge_edge(mat,location)

[i,j]= ind2sub(size(mat),location);
[L,W]= size(mat);
if i == 1 | i == L | j == 1 | j == W
    logic = 1;
else 
    logic = 0;
end

end

2. 转向判别

对于内部点

% 在执行该算法前,必须得线判断当前点是否为边界点。
% 如果不是边界的话,执行下面程序
% 判断当前方向下一点是否为可行点
% next_location 输出下一点坐标
% a 跟新矩阵
% 考虑矩阵内部时,对于每一个当前点方向,接下来可能有两种走向。四个边界点是特殊点
function [next_location,mat,next_direction] = jude_point(mat,temp_location,direction)

[L,W] = size(mat);

[i,j] = ind2sub(size(mat),temp_location);

% avail = 1;
%% first combination up or right
if direction == 10
    if mat(temp_location - 1) == 1  

        next_location = temp_location - 1;
        mat(temp_location) = 0;
        next_direction = 10;
    else
        avail = 1;
       
    end
    
    if exist('avail')
        % 往右手边找是否可行
        
        if mat(temp_location + L) == 1
            
            next_location = temp_location + L;
            mat(temp_location) = 0;
            next_direction = 5;
        else
            
            next_direction = 0;
            mat(temp_location) = 0;
            next_location = temp_location;
        end
    end
end
%% second combination right or down
if direction == 5
    if mat(temp_location + L) == 1

        next_location = temp_location + L;
        mat(temp_location) = 0;
        next_direction = 5;
    else            % 原方向不可行
        avail = 1;
       
    end
    
    
    if exist('avail')   % 如果原方向不可行的话,
        % 往右手边找是否可行
        if mat(temp_location + 1) == 1

            next_location = temp_location + 1;
            mat(temp_location) = 0;
            next_direction = -10;
        else
         
            next_direction = 0;
            mat(temp_location) = 0;
            next_location = temp_location;
           
        end
    end
end

%% third combination down or left
if direction == -10
    if mat(temp_location + 1) == 1

        next_location = temp_location + 1;
        mat(
  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值