小标
2019-01-10
来源 :
阅读 1793
评论 0
摘要:本文主要向大家介绍了 C/C++知识点之C++实现迷宫问题,通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。
本文主要向大家介绍了 C/C++知识点之C++实现迷宫问题,通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。

#include
FILE* fout = fopen("Maze.txt", "r");
assert(fout);
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col;)
{
char ch = fgetc(fout);
if (ch == EOF)
{
cout<<"Init MazeMap fail"<<endl;
exit(false);
}
if (ch == '1' || ch == '0')
{
maze[i * row + j] = ch - '0';
++j;
}
}
}
fclose(fout);}struct Pos{
int _row; //行
int _col; //列};//打印迷宫void PrintMaze(int* maze, int row, int col){
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
{
cout<<maze[i * row + j]<<" ";
}
cout<<endl;
}
cout<<endl;}//判断当前位置是否为0inline bool CheckIsPassWay(int* maze, int row, int col, Pos pos){
if (pos._row < row && pos._col < col && maze[pos._row * col + pos._col] == 0)
{
return true;
}
return false;}//判断迷宫是否有出口bool GetMazePath(int* maze, int row, int col, Pos entry, stack
assert(maze);
path.push(entry);
maze[entry._row * col + entry._col] = 2;//将走过的路标记为2
while (!path.empty())
{
Pos cur = path.top();
Pos next = cur;
if (row-1 == next._row)//找到出口
{
return true;
}
//判断右边是否为0
next = cur;
next._col++;
if (CheckIsPassWay(maze, row, col, next))
{
maze[next._row * row + next._col] = 2;
path.push(next);
continue;
}
//上
next = cur;
next._row--;
if (CheckIsPassWay(maze, row, col, next))
{
maze[next._row * row + next._col] = 2;
path.push(next);
continue;
}
//下
next = cur;
next._row++;
if (CheckIsPassWay(maze, row, col, next))
{
maze[next._row * row + next._col] = 2;
path.push(next);
continue;
}
//左
next = cur;
next._col--;
if (CheckIsPassWay(maze, row, col, next))
{
maze[next._row * row + next._col] = 2;
path.push(next);
continue;
}
path.pop();//四个方向都不通,返回上一步
}
return false;//栈为空,没有找到出口}void TestMaze(){
int maze[10][10] = {};
Pos entry = {1, 0};
stack
InitMaze((int*)maze, 10, 10);
PrintMaze((int*)maze, 10, 10);
GetMazePath((int*)maze, 10, 10, entry, path);
PrintMaze((int*)maze, 10, 10);}int main(){
TestMaze();
return 0;}
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C/C+频道!
喜欢 | 0
不喜欢 | 0
您输入的评论内容中包含违禁敏感词
我知道了

请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号