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