迷宫程序(6)

//迷宫游戏
#ifndef MAZE_H_ 
#define MAZE_H_
 
#include<iostream> 
#include<string> 
#include<vector> 

using namespace std; 

class Maze 
{ 
public: 
Maze();               // 构造函数 
void solve();   // 迷宫求解函数 
private: 
vector<string> cells;            // 用于存储迷宫的各处状态 
int rows, columns;              // 迷宫的行数、列数 
bool exitMaze( int row, int column); // 从位置(row,column)出发,穿越迷宫,成功返回true 
bool valid( int row, int column);    // 用于判断位置(row,column)是否可通行,是返回true 
}; 
#endif   
// 构造函数,对迷宫的状态进行初始化 
Maze::Maze() 
{ 
cout << "请输入迷宫阵列,1代表通路,0代表障碍,每输入一行用回车表确认"<< endl;  
    cout << "输入完成后请输入'ok'以表示之 " << endl; 
// 读入迷宫的状态 
string cellstr; 
cin >> cellstr; 
while (cellstr != "ok") 
{ 
cells.push_back(cellstr); 
columns = cellstr.size(); // 迷宫阵的总列数 
cin >> cellstr; 
} 
rows = cells.size();  // 迷宫阵的总行数 
} 
// 迷宫求解函数 
void Maze::solve() 
{ 
int row, column; 
row = column = 0;  // 设置出发点为(0,0)位置 
bool done = exitMaze( row, column); 
// 穿越成功,显示穿越路径,否则报道迷宫无法穿越 
if (done) 
{ 
cout << "恭喜!成功穿过迷宫!穿越路径为:" << endl; 
for (int i = 0; i < rows; ++i ) 
{ 
for (int j = 0; j < columns; ++j) 
cout << cells[i][j]; 
cout << endl; 
}// end for 
}// end if 
else 
cout << "对不起,此迷宫无法穿越" << endl; 
} 

// 从位置(row,column)出发,穿越迷宫,成功返回true 
bool Maze::exitMaze( int row, int column) 
{ 
bool done = false; 
// 如果位置(row,column)可通行,标记之,并依次向四周搜索着前进 
if ( valid(row, column) ) 
{ 
  cells[row][column] = 'B';  // 走过的位置标记为'B 
// 抵达终点时表示穿越完成 
if ( row == (rows - 1) && column == (columns - 1) ) 
done = true; 
else 
{ 
done = exitMaze ( row , column + 1);  // 未到达终点前,首先选择向右走
if (!done)        // 右走失败,转向下走
done = exitMaze ( row + 1, column); 
            if (!done)      // 右走、下走失败,转向左走
done = exitMaze ( row, column - 1); 

            if (!done)      // 右走、下走、左走均失败,转向上走
done = exitMaze ( row - 1, column); 
} 
if (done) 
cells[row][column] = 'P';  // 正确的路径标记为'P' 
} 
return(done); 
} 
// 判断位置(row,column)是否可通行,是则返回true 
bool Maze::valid( int row, int column) 
{ 
bool path = false; 
// 如果位置(row,column)在迷宫内,且该处可通行 
if ( row >= 0 && row < rows && column >= 0  
&& column < columns && cells[row][column] == '1' ) 
path = true; 
return path; 
} 

//maze_main.cpp文件 
// 迷宫模拟Maze类的测试函数 

int main() 
{ 
cout << "****************欢迎使用迷宫模拟程序*************" << endl;; 
Maze MazeExc; 
MazeExc.solve(); 
system("pause");  
return 0; 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值