這期內容當中小編將會給大家帶來有關怎么在C++中利用遞歸走迷宮,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
1、文件中第一行分別放置的是地圖的行數和列數
2、其中1表示墻,即路不通,0表示路,即通路
3、程序運行結束后用2標記走過的路徑
4、當走到“死胡同”時用3標記此路為死路
5、每到一個點,按照 左 上 右 下 的順序去試探
6、沒有處理入口就是"死胡同"的極端情況
maze.h
#ifndef _MAZE_H_
#define _MAZE_H_
#include <fstream> // ifstream
#include <iostream>
#include <cassert>
#include <string>
using namespace std;
// 坐標類
class Seat
{
public:
Seat(int _x, int _y)
:x(_x)
,y(_y)
{ }
int x;
int y;
};
// 迷宮類
class Maze
{
private:
int** _map; // 指向地圖的指針
int _row; // 存放地圖的行數
int _col; // 存放地圖的列數
public:
// 構造函數 讀取文件里的地圖 和行數
Maze(const string& filePath);
private:
// 判斷是否是路
bool IsPass(Seat& entry);
public:
// 開始走
bool PassMaze( Seat& entry);
// 打印地圖
void PrintMap();
// 析構 釋放空間
~Maze();
};
#endifmaze.cpp
// 遞歸實現迷宮
#include "maze.h"
// 判斷是否是路
bool Maze::IsPass( Seat& Entry)
{
if (_map[Entry.x][Entry.y] == 0)
{
return true;
}
return false;
}
// 構造函數 讀取文件里的地圖 和行數
Maze::Maze(const string& filePath )
{
ifstream read(filePath);
string str_row_col, str_temp;
// 讀取第一行
getline(read, str_row_col);
// 獲取行
str_temp = str_row_col.substr(0, str_row_col.find_first_of(','));
_row = atoi(str_temp.c_str());
// 獲取列
str_temp = str_row_col.substr( str_row_col.find_first_of(',')+1);
_col = atoi(str_temp.c_str());
// 為地圖分配空間
_map = new int*[_row];
for (int index = 0; index < _col; ++index)
{
_map[index] = new int[_col];
}
int index_col = 0;
int index_row = 0;
// 填充地圖
while (!read.eof())
{
// 獲取一行
getline(read, str_temp);
char * line = (char*)str_temp.c_str();
while ((*line) != '\0')
{
if (*line == '0' || *line == '1')
{
_map[index_row][index_col++] = *line - '0';
}
++line;
}
++index_row;
index_col = 0;
}
// 關閉文件
read.close();
}
// 開始走
bool Maze::PassMaze( Seat& Entry)
{
// 判斷是否走到出口
if (Entry.x < 0 || Entry.y < 0 || Entry.y >=_row)
{
return true;
}
if (IsPass(Entry))
{
// 將走過的路置為2
_map[Entry.x][Entry.y] = 2;
// 向左走
Seat left(Entry.x, Entry.y-1);
if (PassMaze(left))// 遞歸調用
{
return true;
}
// 向上走
Seat up(Entry.x-1, Entry.y);
if (PassMaze(up)) // 遞歸調用
{
return true;
}
// 向右走
Seat right(Entry.x, Entry.y+1);
if (PassMaze(right)) // 遞歸調用
{
return true;
}
// 向下走
Seat down(Entry.x+1, Entry.y);
if (PassMaze(down))
{
return true;
}
// 走到此處說明是死路 置為3
_map[Entry.x][Entry.y] = 3;
}
return false;
}
// 打印地圖
void Maze::PrintMap()
{
for (int row = 0; row<_row; ++row)
{
for (int col = 0; col<_col; ++col)
{
cout << _map[row][col] << " ";
}
cout <<endl;
}
cout <<endl;
}
// 釋放空間
Maze::~Maze()
{
for (int idx = 0; idx < _row; ++idx )
{
delete[] _map[idx];
}
delete[] _map;
_map = NULL;
}上述就是小編為大家分享的怎么在C++中利用遞歸走迷宮了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。