使用栈解决迷宫问题
2016-09-06 16:20
295 查看
/****************************************************************************************** Copyright (c), Inc.(2016), All rights reserved. Purpose: 使用栈解决迷宫问题 Author: 迷宫实现 Created Time: 2016_9 ******************************************************************************************/ #pragma once #include <stack> struct Pos { int row; // 行 int col; // 列 }; int** CreateMaze(int n) { int** ppMaze = new int* ; for (int i = 0; i < n; ++i) { ppMaze[i] = new int ; memset(ppMaze[i], 0, sizeof(int)*n); } return ppMaze; } Pos InitMaze(int** ppMaze, int n) { Pos entry; entry.row = 2; entry.col = 0; FILE* fOut = fopen("MazeMap.txt", "r"); for (int i = 0; i < n; ++i) { for (int j = 0; j < n;) { char ch = fgetc(fOut); if (ch == '0' || ch == '1') { ppMaze[i][j++] = ch - '0'; } else if (ch == EOF) { cout<<"Maze Map Error"<<endl; } } } fclose(fOut); return entry; } void PrintMaze(int** ppMaze, int n) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { cout<<ppMaze[i][j]<<" "; } cout<<endl; } cout<<endl; } bool CheckIsAccess(int** ppMaze, int n, Pos pos) { if (pos.col > 0 && pos.col < n && pos.row > 0 && pos.row < n && ppMaze[pos.row][pos.col] == 0) { return true; } return false; } bool Maze(int** ppMaze, int n, const Pos& entry, stack<Pos>& path) { assert(entry.col < n && entry.row < n); Pos cur = entry; ppMaze[cur.row][cur.col] = 2; path.push(cur); while (!path.empty()) { Pos next = path.top(); // // 出口在最后一行 // if (next.row == n-1) return true; // 上 next.row -= 1; if (CheckIsAccess(ppMaze, n, next)) { ppMaze[next.row][next.col] = 2; path.push(next); continue; } // 右 next = path.top(); next.col += 1; if (CheckIsAccess(ppMaze, n, next)) { ppMaze[next.row][next.col] = 2; path.push(next); continue; } // 下 next = path.top(); next.row += 1; if (CheckIsAccess(ppMaze, n, next)) { ppMaze[next.row][next.col] = 2; path.push(next); continue; } // 左 next = path.top(); next.col -= 1; if (CheckIsAccess(ppMaze, n, next)) { ppMaze[next.row][next.col] = 2; path.push(next); continue; } Pos tmp = path.top(); ppMaze[tmp.row][tmp.col] = 3; path.pop(); } return false; } void TestMaze() { int n = 10; int** ppMaze = CreateMaze(n); Pos entry = InitMaze(ppMaze, n); PrintMaze(ppMaze, n); stack<Pos> path; Maze(ppMaze, n, entry, path); PrintMaze(ppMaze, n); cout<<"Path:"; while (!path.empty()) { const Pos& pos = path.top(); cout<<"("<<pos.row<<","<<pos.col<<")"<<"<-"; path.pop(); } cout<<"Entry"<<endl; }
相关文章推荐
- libvirt依赖的库
- Spring BeanUtils.copyProperties和apache commons-beanutils
- BroadcastReceiver学习之路(01)之普通广播及广播简介
- 使用北通手柄控制turtlesim运动
- 【递归、二分查找】数字在排序数组中出现的次数
- python gui 之 tkinter库
- Linux kernel Low Level debug
- tomcat7+jdk的keytool生成证书 配置https
- Java程序员的10个日志技巧
- ios上取得设备唯一标志的解决方案
- zabbix--从入门到精通之zabbix历史数据
- Java Service Wrapper简介与使用 linux
- 单Activity多Fragment模式快速构建一个App
- 全球历次房地产大泡沫如何破裂,看中国未来房价走势
- PsychoPy入门_05_循环和随机
- oracle系统包--dbms_output的用法
- JTA 深度历险 - 原理与实现
- 存储过程
- Mac安装Boost C++库
- Hi3516A开发--根文件系统