迷宫老鼠
#include <iostream> #include <stack> using namespace std; struct position { int row; int col; }; bool findPath(int** maze, int row, int col) //maze已经扩充行和列,形成外围 { auto path = new stack<position>; position offset[4]; offset[0].row = 0; offset[0].col = 1; //right offset[1].row = 1; offset[1].col = 0; //down offset[2].row = 0; offset[2].col = -1; //left offset[3].row = -1; offset[3].col = 0; //up for (int i = 0; i < row; i++) { maze[i][0] = maze[i][col - 1] = 1; } for (int i = 0; i < col; i++) { maze[0][i] = maze[row - 1] [i] = 1; } position here; here.col = here.row = 1; maze[1][1] = 1; int option = 0; //记录下一步的位置,下一步位置为 here + offse[option] int lastOption = 3; //每一个位置总共有四次选择,right、down、left、up while(here.col != col - 2 || here.row != row - 2) //没有到达出口 { int r, c; while (option <= lastOption) { r = here.row + offset[option].row; c = here.col + offset[option].col; if (maze[r][c] == 0) break; option++; } if (option <= lastOption) { path -> push(here); here.row = r; here.col = c; maze[r][c] = 1; option = 0; } else //here的周围除了来路全是障碍,或回到原点 { if (path -> empty()) //如果没有到达出口的路径,here会回到位置(1, 1),path为空,没有位置可以返回 return false; //没有到达出口 position next = path -> top(); path -> pop(); if (next.row == here.row) //由于来路已经走过,其可选路径不再为四次 option = 2 + next.col - next.col; else option = 3 + next.row - here.row; here = next; } } path -> push(here); if (!path -> empty()) cout << '(' << path -> top().row << ", " << path -> top().col << ')'; path -> pop(); while(!path -> empty()) { cout << " → " << '(' << path -> top().row << ", " << path -> top().col << ')' ; path -> pop(); } delete path; return true; } int main() { int row, col; cin >> row >> col; int ** maze = new int*[row + 2]; for (int i = 0; i < row + 2; i++) maze[i] =new int[col + 2]{1}; for (int i = 1; i < row + 1; i++) for (int j = 1;j < col + 1; j++) { cin >> maze[i][j]; } findPath(maze, row + 2, col + 2); for (int i = 0; i < row + 2; i++) delete[] maze[i]; delete[] maze; }
posted on 2020-09-09 19:38 waterrzhang 阅读(85) 评论(0) 编辑 收藏 举报