码迷,mamicode.com
首页 > 编程语言 > 详细

C++实现迷宫问题

时间:2016-05-22 00:53:37      阅读:650      评论:0      收藏:0      [点我收藏+]

标签:   迷宫问题   

#include <iostream>

using namespace std;

#include <stack>

#include <assert.h>


//初始化迷宫

void InitMaze(int* maze,int row, int col)

{

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;

}


//判断当前位置是否为0

inline bool CheckIsAccess(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<Pos>& path)

{

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 (CheckIsAccess(maze, row, col, next))

{

maze[next._row * row + next._col] = 2;

path.push(next);

continue;

}


//上

next = cur;

next._row--;

if (CheckIsAccess(maze, row, col, next))

{

maze[next._row * row + next._col] = 2;

path.push(next);

continue;

}


//下

next = cur;

next._row++;

if (CheckIsAccess(maze, row, col, next))

{

maze[next._row * row + next._col] = 2;

path.push(next);

continue;

}


//左

next = cur;

next._col--;

if (CheckIsAccess(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<Pos> path;//将走过的路径保存在栈path中

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;

}

技术分享

本文出自 “zgw285763054” 博客,请务必保留此出处http://zgw285763054.blog.51cto.com/11591804/1775724

C++实现迷宫问题

标签:   迷宫问题   

原文地址:http://zgw285763054.blog.51cto.com/11591804/1775724

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!