#include<iostream> #include<assert.h> #include<stack> using namespace std; //求解路径的基本思想:1.如果当前路径能够通过,将当前路经进行压栈,为了回退(回溯法),并将走过的路标记成2 不能走1,0可以走 //2.如果当前路径上下左右都不能通过,则出栈(回溯)并且将当前路径标为3 即将回溯路径标记为3 //3.栈为空(表示回到起点)也表示没有出路 #define M 10 #define N 10 class Maze { public://内部类,作用域在maze类中 struct Pos { size_t _row; size_t _col; }; typedef struct Pos Pos; Maze(int maze[M][N])//初始化迷宫 { for (size_t i = 0; i < M; i++) { for (size_t j = 0; j < N; j++) { _maze[i][j] = maze[i][j]; //_maze[i][j]=maze[i*N+j];二维数组其实是按一维数组的顺序排列的 } } } bool CheckAccess(Pos next) { if ((next._row >= 0) && (next._row < M) && (next._col >= 0) && (next._col < N)&&(_maze[next._row][next._col]==0)) { return true; } return false; } bool GetMazePath(Pos entry) { stack<Pos> paths; paths.push(entry); _maze[entry._row][entry._col] = 2;//走过的路标记为2 while (!paths.empty())//如果栈为空,就表示找不到出口 { //栈顶的坐标,就是当前位置 Pos cur = paths.top(); //试探四个方向 if (((cur._row == M - 1) || (cur._col == N- 1))&& ((cur._col!=entry._col)&&(cur._row!=entry._row))) { return false; } //上 Pos next = cur; next = cur; next._row += 1; if (CheckAccess(next)) { paths.push(next); _maze[next._row][next._col] = 2; continue; } //下 next = cur; next._row -= 1; if (CheckAccess(next)) { paths.push(next); _maze[next._row][next._col] = 2; continue; } //左 next = cur; next._col -= 1; if (CheckAccess(next)) { paths.push(next); _maze[next._row][next._col] = 2; continue; } //右 next = cur; next._col += 1; if (CheckAccess(next)) { paths.push(next); _maze[next._row][next._col] = 2; continue; } //走到此处说明next位置,四个方向都走不通 回溯 Pos back = paths.top(); // 将走不通的标记为3,即将回溯的路记为3 _maze[back._row][back._col] = 3; paths.pop(); } return false; } void print() { for (size_t i = 0; i < M; i++) { for (size_t j = 0; j < N; j++) { cout << _maze[i][j] << " "; } cout << endl; } cout << endl; } protected: int _maze[M][N]; }; void Test() { int a[10][10] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 }; Maze m(a); m.print(); Maze::Pos entry; entry._row = 2; entry._col = 0; m.GetMazePath(entry); m.print(); }
我的生物钟调不过来了,下午困,晚上睡不着。