初级版迷宫问题(栈的应用)

发布时间:2020-08-05 13:30:16 作者:hhaxy77
来源:网络 阅读:433
 
/*
 (一)初级迷宫问题:
  0:代表通
  1:代表不通
  求迷宫的通路
 (二)步骤:
  1.创建迷宫
     * 从文件中读取迷宫
     * 开辟二维数组存放迷宫
  2.寻找通路
     * 检查某位置是否为通
     * 出口位置判断
     * 走过的路用2标记
     * 利用栈回溯
 (三)问题
  1.解决回溯中重复探测:递归
  2.最优解:迷宫的最短通路
*/

#include <iostream>
#include <stdlib.h>
#include <assert.h>
#include <stack>
#define _CRT_SECURE_NO_WARNINGS 1
#define N 10
using namespace std;
struct Pos
{
 size_t _row;  //行
 size_t _col;  //列
};
void GetMap(int* m, int n)
{
 int i = 0;
 int j = 0;
 assert(m);
 FILE* fin = fopen("C:\\学习\\code\\数据结构\\MazeMap\\MazeMap.txt","r");
 assert(fin);
 for(i = 0; i < n; i++)
 {
  for(j = 0; j < n;)
  {
   char ch = fgetc(fin);
   if(ch == '0'||ch == '1')
   {
    m[i*n+j] = ch - '0';
    j++;
   }
  }
 }
}
void PrintMap(int* m, int n)
{
 assert(m);
 int i = 0;
 int j = 0;
 for(i = 0; i < n; i++)
 {
  for(j = 0; j < n; j++)
  {
   cout<<m[i*n+j]<<' ';
  }
  cout<<endl;
 }
}
bool CheckIsAccess(int* m, int n, const Pos& next)
{
 if(next._row >= 0 && next._row < n 
  && next._col >= 0 && next._col < n
  && m[next._row*n+next._col] == 0)
 {
  return true;
 }
 else
 {
  return false;
 }
}
bool SearchMazePath(int* m, int n, Pos enrty,stack<Pos> paths)
{
 assert(m);
 paths.push(enrty);
 while(!paths.empty())
 {
  Pos cur = paths.top();
  m[cur._row * n + cur._col] = 2;
  //检查是否找到出口
  if(cur._row == n-1)
  {
   return true;
  }
  Pos next = cur;
  //上
  next._row--;
  if(CheckIsAccess(m, n, next))
  {
   paths.push(next);
   continue;
  }
  next = cur;
  //右
  next._col++;
  if(CheckIsAccess(m, n, next))
  {
   paths.push(next);
   continue;
  }
  next = cur;   //next归位
  //下
  next._row++;
  if(CheckIsAccess(m, n, next))
  {
   paths.push(next);
   continue;
  }
  next = cur;
  //左
  next._col--;
  if(CheckIsAccess(m, n, next))
  {
   paths.push(next);
   continue;
  }
 
  paths.pop();
 }
 return false;
}
int main()
{
 int map[N][N]= {0};
 GetMap((int*)map, N);
 PrintMap((int*)map, N);
 Pos enrty = {2,0};
 stack<Pos> paths;
 cout<<endl;
 cout<<SearchMazePath((int*)map,N,enrty,paths);
 cout<<endl;
 PrintMap((int*)map, N);
 system("pause");
 return 0;
}

推荐阅读:
  1. zlib 初级应用
  2. 以栈解决迷宫问题

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

栈的应用 迷宫问题

上一篇:wuzhicms 查看模板中的所有可用变量和值

下一篇:Web 入门开发简要路线图

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》